Reputation: 153
I want to delete an item from arrayList and update it after delete. The query is performing delete operation but the list is not getting updated. Below is the onItemLongClickListener code.
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
help.deleteEntry(position);
adapter.remove(adapter.getItem(position));
adapter.notifyDataSetChanged();
Toast.makeText(Search.this, "Delete..", Toast.LENGTH_SHORT).show();
return true;
}
});
Delete code of DatabaseHelper.
public void deleteEntry(long id) {
// delete row in user table based on id
SQLiteDatabase db = this.getReadableDatabase();
db.delete(TABLE_NAME,KEY_ID + " = " + id,null);
}
Upvotes: 1
Views: 3195
Reputation: 2817
I notice two things here first don't pass position to delete row from the database as the id is auto increment and secondly for delete you should getWriteableDatabase()
So your code should be like this
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Obj obj = adapter.getItem();
help.deleteEntry(obj.getId());
adapter.remove(adapter.getItem(position));
adapter.notifyDataSetChanged();
Toast.makeText(Search.this, "Delete..", Toast.LENGTH_SHORT).show();
return true;
}
});
In your deleteEntry()
use this
SQLiteDatabase db = this.getWriteableDatabase();
Upvotes: 0
Reputation: 1770
write a method in adapter to remove the item:
public removeItem(int position){
yourArrayList.remove(position);
notifyDataSetChanged();
}
And call this method from onItemLongClick Of listview:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
adapter.removeItem(position);
}
});
Upvotes: 3