从列表视图中删除该项目时,该项目会在那时被删除,但是回到活动时,该项目会重新出现。 这是我的Main2Activity代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
position = intent.getIntExtra("position", 0);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItem);
listView.setAdapter(adapter);
viewData1();
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int pos, long id) {
final int itemToDelete = pos;
new AlertDialog.Builder(Main2Activity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this location?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
listItem.remove(itemToDelete);
databaseHelper1.deleteLocation(itemToDelete, position);
adapter.notifyDataSetChanged();
}
}
)
.setNegativeButton("No", null)
.show();
return true;
}
});
}
private void viewData1() {
Cursor cursor = databaseHelper1.viewData1(position);
if (cursor.getCount() == 0) {
Toast.makeText(this, "No data to show", Toast.LENGTH_SHORT).show();
} else {
while (cursor.moveToNext()) {
Log.i("message", "Data got");
listItem.add(cursor.getString(1));
}
adapter.notifyDataSetChanged();
}
}
DatabaseHelper:
public void deleteLocation(int itemToDelete,int position)
{
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String itemDelete = Integer.toString(itemToDelete);
Log.i("itemdel",itemDelete);
if(position ==0)
{
String Id = (ID1);
Log.i("Id",Id);
String query = " Delete from "+DB_TABLE1 + " where "+ Id + " = " + itemDelete;
sqLiteDatabase.execSQL(query);
sqLiteDatabase.delete(DB_TABLE1,ID1 + " = "+ itemDelete, null);
sqLiteDatabase.compileStatement(query);
Log.i("del"," executed")
}
}
public Cursor viewData1(int position)
{
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = null;
if (position ==0)
{
String query = "Select * from " + DB_TABLE1;
cursor = sqLiteDatabase.rawQuery(query, null);
}
return cursor;
}
会发生什么: 删除之前:
删除花园后:
在重新启动活动时:
如何将删除提交到数据库?谢谢。
答案 0 :(得分:1)
您的问题是您假设位置(传递给onItemLongClick方法的第3个参数)直接与该行的ID相关。
您不能依赖位置和ID之间的关联。
列表中的第一个位置将位于位置0。分配的最低ID(除非强制)将为1。但是,即使最初添加1也不是解决方案。一旦删除列表中最后一项以外的任何内容,ID列表中就会省略 id ,并且您可能无法删除行或删除其他行。
最明智/最简单的解决方法是利用CursorAdapter即SimpleCursorAdapter,在这种情况下, onItemClick 和 onItemLongClick (长l)的第四个参数将是实际的 id 。但是,要使用CursorAdapter,您必须将id列命名为 _id (因此,为什么会有常量 BaseColumns._ID )。
使用AS提取列时,您始终可以重命名该列。 SELECT rowid AS _id, * FROM the_table;
(它将选择所有现有列和id列)。
这里是指向其他适配器Deleting item from ListView and Database with OnItemClickListener
选项的更全面答案的链接。