Skip to content Skip to sidebar Skip to footer

How To Delete Item From Listview?

I fetch data from SQLite in Listview .I need to delete this item when user click on check box and press the delete button or only clicking on the check box, I don't understand how

Solution 1:

You need to change the getView prototype from:

public View getView(int position, View convertView, ViewGroup parent)

to

public View getView(finalint position, View convertView, ViewGroup parent)

Then add to your viewHolder.checkbox.setOnCheckedChangeListener listener:

Model element = (Model) viewHolder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
InteractiveArrayAdapter.this.remove(InteractiveArrayAdapter.this.getItem(position));
list.remove(position); //here consider whether you can afford changing list// If you want to add code to remove the element from the database too

I have not tried it myself, but it seems that will work.

EDIT: Following you request I am adding the code to delete the entry from your database:

In your MySQliteHelper class add the following method:

publicvoiddeleteByName(String name) {          
   SQLiteDatabase db= this.getWritableDatabase();
   db.delete(TABLE_NAME, COLUMN1 +"=?", newString [] { name });
   db.close();
}

Then change the code of the listener:

Model element = (Model) viewHolder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
InteractiveArrayAdapter.this.remove(InteractiveArrayAdapter.this.getItem(position));

MySQLiteHelper m = new MySQLiteHelper(InteractiveArrayAdapter.this.context);
m.deleteNyName(list.get(position).toString());
list.remove(position); //here consider whether you can afford changing list

Here I assume your names are unique. In case this is not true you will need to refactor your Model class (which, by the way, is already too confusing and I am just wild guessing that model.toString() will return the string of the name).

Solution 2:

OnListItemClick just remove your list element like ...

list.remove(position) 

and then just refresh your listview using adpter.notifyDataSetChanged();

and also remove from database from get value or using Position.

Post a Comment for "How To Delete Item From Listview?"