我正在尝试通过在列表视图上长按从数据库中删除项目。当我单击删除时,该项目将从列表视图中删除,并显示一条Toast消息已删除,但是如果我移至其他“活动”并返回,则该项目仍在我的列表视图中退出。如何从数据库中删除项目
这是我的代码
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(final AdapterView<?> arg0, View arg1, final int arg2, final long arg3) {
final AlertDialog.Builder delete = new AlertDialog.Builder(AddCount.this);
delete.setIcon(R.drawable.ic_baseline_delete_24);
delete.setTitle("Are you sure");
delete.setMessage("Do you want to delete this item?");
delete.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
DbHandler db = new DbHandler(getApplicationContext());
db.deleteData(arg2 + "");
userList.remove(arg2);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT).show();
}
});
delete.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
delete.show();
return true;
}
});
Dbhandler.java(SQLite数据库)
public void deleteData(String id)
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_Inputs, "id = ? ", new String[]{id});
db.close();
}
答案 0 :(得分:1)
https://developer.android.com/reference/android/widget/AdapterView.OnItemLongClickListener
在此链接中,他们将方法定义如下: onItemLongClick(AdapterView <?>父级,视图,int位置,长id)。
您的定义: public boolean onItemLongClick(final AdapterView <?> arg0,View arg1,final int arg2,final long arg3)。
您使用了“ final int arg2”。由于无法重新分配使用final关键字定义的参数,因此可能会导致问题。尝试定义没有最终关键字的方法,看看是否可行。