這個問題之前可能被問到過,但其他問題沒有類似的代碼。我的SQLite表非常簡單:我擁有的是我的ID和TO_DO_NAME列,並且我想在ListItem調用onLongClick()時刪除一行。我已經實現了長時間點擊功能,但是當我重新啓動應用程序時,相同的項目在那裏。這是我的DatabaseHelper:我無法從我的Android SQLite數據庫中刪除一行
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "todo.db";
public static final String TABLE_NAME = "student";
public static final String ID = "id";
public static final String TO_DO = "todo";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String CREATE_TO_DO_TABLE = "CREATE TABLE "
+ TABLE_NAME
+ "("
+ ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ TO_DO
+ " TEXT"
+ ")";
sqLiteDatabase.execSQL(CREATE_TO_DO_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean insertData(String todo) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TO_DO, todo);
long result = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Cursor data = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
}
這是我更新方法,它採用了單排的護理刪除:
public int itemDeleteFromDatabase(long id) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
int deleteFromDatabase = database.delete(TABLE_NAME, ID + "=" + id, null);
listItems.setAdapter(adapter);
return deleteFromDatabase;
}
我從我的列表項長按調用方法:
listItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int position, long id) {
toDoItems.remove(position);
itemDeleteFromDatabase(position);
MainActivity.this.adapter.notifyDataSetChanged();
return true;
}
});
就像我說的,它仍然存在。
UPDATE
這是我從添加數據:
public void addItem(View v){
EditText newItem = (EditText) findViewById(R.id.itemInputEditText);
String item = newItem.getText().toString();
databaseHelper.insertData(item);
adapter.add(item);
newItem.setText("");
}
從哪裏添加數據到你的sqlite? –
從我的textview動態地。 –
張貼代碼請 –