gpt4 book ai didi

java - 从 Android Studio 上的 sqlite 表中删除行不起作用

转载 作者:行者123 更新时间:2023-12-01 16:51:47 26 4
gpt4 key购买 nike

在android studio中,我有一个sqlite表DatabaseHelper,其创建为:

public class DatabaseHelper extends SQLiteOpenHelper {
private static final int BD_version = 1;
public static final String TABLE_NOMBRE = "SQLiteGPS";
public static final String COLUMN_ID = "id";
public static final String COLUMN_DIRECCION = "direccion";

public DatabaseHelper(Context context) {
super(context, TABLE_NOMBRE, null, BD_version);
}

@Override
public void onCreate(SQLiteDatabase db) {
String sql = " CREATE TABLE " + TABLE_NOMBRE
+ "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
+ COLUMN_DIRECCION + " VARCHAR); ";
db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS SQLiteGPS";
db.execSQL(sql);
onCreate(db);
}

public boolean addData (String insertar){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_DIRECCION,insertar);
long result = db.insert(TABLE_NOMBRE,null,contentValues);
if(result == -1){
return false;
}else{
return true;
}
}

public Cursor getListaContenidos(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM "+ TABLE_NOMBRE,null);
return data;
}

public void deleteItemDB(String itemID){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NOMBRE + " WHERE " + COLUMN_DIRECCION + "='" + itemID + "'");
db.close();
}
}

我只需要删除第一行,因为我正在使用这段代码,但它不起作用,我没有错误,只是没有删除一行

 DatabaseHelper miBD = new DatabaseHelper(this);

bBorrarItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
miBD.deleteItemDB("1"); // set Dynamic
Toast.makeText(MainActivity.this,"Borrado el 1er item de la Tabla",Toast.LENGTH_LONG).show();
}
});

我的错误是什么?

最佳答案

I just want to delete the first row!

删除第一行与删除 id = 1 的行不同;要删除第一行,则需要先使用光标获取其 id,然后将其删除。

// Get the cursor 
Cursor cursor = getListaContenidos();

// Move to the first row
cursor.moveToFirst();

// Get the column ID of the first row
int id = cursor.getInt(cursor.getColumnIndex(COLUMN_DIRECCION));

// perfrom delete
deleteItemDB(String.valueOf(id));

关于java - 从 Android Studio 上的 sqlite 表中删除行不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61669973/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com