Skip to content Skip to sidebar Skip to footer

Deleting An Item From Listview (using Sqlite) Results In Only Removing It From Listview.can't Delete It From Database

When I try to delete an item in list view ,it removes it from list view but when I add a new item or run the application again the items is still there.I can't delete it from datab

Solution 1:

the problem you have is the call of your method delete, it should be like this :

public long deleteItem(myItems itemToDelete) {
    try {
             return sqlDatabase.delete(DATABASE_TABLE,COLUMN_ID + " = ?",newString[]{itemToDelete.getID()});
            }
            catch (Exception e)
            {
                Log.e("DB ERROR", e.toString());
                e.printStackTrace();
                return -1;
            }
}

and when you press the YESButton of AlertDialog to confirm delete you should delete the item from database, and then reload items from database and notify the adapter of your list to refresh it with the new data :

myItemsselectedItem= adapter.getItem(position);
longrows= sqlHandler.deleteItem(selectedItem);
if(rows>0) {
    //get new items from database 
    adapter.setItems(getItemsFromDatabase());
    adapter.notifyDataSetChanged();
}

the item will be deleted from database, and the listView will be refreshed with the new data

Solution 2:

I believe the error is here:

new DialogInterface.OnClickListener() {
        publicvoidonClick(DialogInterface dialog, int id) { //<--- rename this to buttonId
          sqlHandler=new SqlHandler(getApplicationContext());
          sqlHandler.deleteRecord(id);  //<---- This "id" is the button that was clicked, not your item ID

I suppose that you wanted to use the otherid variable, but even then, I'm not sure that's the one you really want either (it might be). From your code I couldn't quickly tell where the real ID is though.

Post a Comment for "Deleting An Item From Listview (using Sqlite) Results In Only Removing It From Listview.can't Delete It From Database"