How to delete item from listView?

后端 未结 2 611
傲寒
傲寒 2021-01-23 05:38

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 und

相关标签:
2条回答
  • 2021-01-23 06:09

    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.

    0 讨论(0)
  • 2021-01-23 06:15

    You need to change the getView prototype from:

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

    to

    public View getView(final int 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:

    public void deleteByName(String name) {          
       SQLiteDatabase db= this.getWritableDatabase();
       db.delete(TABLE_NAME, COLUMN1 +"=?", new String [] { 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).

    0 讨论(0)
提交回复
热议问题