SQLite Database item comes back after restarting Activity even though it was deleted

问题: On deleting the item from the Listview the item gets deleted at that time, but on coming back to the activity the item reappears. This is my Main2Activity code: protecte...

问题:

On deleting the item from the Listview the item gets deleted at that time, but on coming back to the activity the item reappears. This is my Main2Activity code:

 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;
}

What happens is: Before Deleting:

After Deleting garden:

On restarting activity:

How do I commit the delete to the database? Thanks.


回答1:

Your issue is that you are assuming that position (3rd parameter passed to the onItemLongClick method) directly relates to the id of the row.

You cannot rely on a correlation between position and id.

The first position in the list will be at position 0. The lowest ID allocated (unless forced) will be 1. However adding 1 is not a solution as even though it may initially work. As soon as you delete anything other than the last item in the list then an id is omitted from the list of id's and you may not delete a row or you may delete a different row.

The most sensible/easiest fix is to utilise a CursorAdapter i.e. SimpleCursorAdapter in which case the 4th parameter to onItemClick and onItemLongClick (long l) will be the actual id. However, to utilise a CursorAdapter you MUST have the id column named as _id (hence why there is the constant BaseColumns._ID).

You could always rename the column when extracting it using AS e.g. SELECT rowid AS _id, * FROM the_table; (which will select all existing columns AND the id column).

Here's a link to a more comprehensive answer with options for other adapter Deleting item from ListView and Database with OnItemClickListener

  • 发表于 2019-01-01 07:55
  • 阅读 ( 204 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除