[英]Deleting item from listview and database
I have a list view that has a list of a user's data. 我有一个列表视图,其中包含用户数据的列表。 When I long click on the listview item, I want the item to delete. 当我长时间单击列表视图项时,我希望将其删除。 I have it already so that the item looks like it deletes, but when I go back and refresh the page or reopen the page later, the data is still there. 我已经拥有它,因此该项目看起来像已删除,但是当我返回并刷新页面或稍后重新打开页面时,数据仍然存在。 I know that's because the item in the database isn't deleted - only the listview one is. 我知道那是因为数据库中的项目没有被删除-只有列表视图被删除了。 I don't know how to delete the database object as well, I've tried a couple of different ways by looking at previous threads but they don't seem to work. 我也不知道如何删除数据库对象,我通过查看以前的线程尝试了几种不同的方法,但是它们似乎不起作用。
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, final long id) {
AlertDialog.Builder adb = new AlertDialog.Builder(PreviousPractices.this);
adb.setTitle("Delete?");
adb.setMessage("Delete this?");
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Yes", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
db.remove(id);
ArrayOfPractices.remove(positionToRemove);
adapter.notifyDataSetChanged();
}
});
adb.show();
return false;
}
});
This is the first way I've tried.My remove method in the database class is: 这是我尝试过的第一种方法。我在数据库类中的remove方法是:
public void remove(long id){
SQLiteDatabase db = this.getWritableDatabase();
String string =String.valueOf(id);
db.delete(DATABASE_TABLE, KEY_ID + " = " + id, null);
}
A second way I've tried is by using this method: 我尝试过的第二种方法是使用此方法:
public void deletePractice(Practice practice) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(DATABASE_TABLE, KEY_ID + " = ?",
new String[]{String.valueOf(practice.getID())});
db.close();
}
and then calling it by: 然后通过以下方式调用它:
public void onClick(DialogInterface dialog, int which) {
db.deletePractice(pList.get(position));
ArrayOfPractices.remove(positionToRemove);
adapter.notifyDataSetChanged();
}
Your code of db.delete(DATABASE_TABLE, KEY_ID + " = " + id, null);
您的db.delete(DATABASE_TABLE, KEY_ID + " = " + id, null);
is fine. 很好
However for debugging do this, and notify us. 但是,为了进行调试,请通知我们。
int rowsDeleted = db.delete(DATABASE_TABLE, KEY_ID + " = " + id, null);
Log.d(TAG, "Deleted rows = " + rowsDeleted);
Basically tell us the number of rows affected. 基本上告诉我们受影响的行数。 I suspect 0 rows, if so, then DATABASE_TABLE is wrong or variable id
is not the correct value for the ID. 我怀疑是0行,如果是这样,则DATABASE_TABLE错误或变量id
不是该ID的正确值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.