Hey guys I have a list menu that’s created from a strings column of a database . When a user clicks on a list menu item, they will delete it. I’m doing this by passing the list item position to the delete function on my DBAdapter.
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
db.deleteContact(position);
}
The function finds the corresponding row index and deletes it.
public boolean deleteContact(long rowId) {
return db.delete(DATABASE_TABLE, KEY_NAME + "=" + rowId, null) > 0;
}
The problem (which is probably very obvious to most of you) is that when a user deletes, lets say list menu item 2, and the corresponding index is deleted from the table, the list menu refreshes and the item previously in position 3 is now in position 2. if the user tries to delete that, the delete function receives “2” as a parameter but the index of the desired row to be deleted is 3.
I know this is a silly problem, but can someone suggest an effective workaround? thanks
You shouldn’t delete by position. The
idprovided in theonListClickItemmethod is here to help you. Replace your code above by:provided that your
KEY_NAMEis the primary key of your table. If not, replaceKEY_NAMEby the name of the primary key field.