Kgrover
Kgrover

Reputation: 2116

Not Able to delete listItem from ListView Android

I am using this code in order to do this, but it is not functional at this point. I can select the checkbox, and when I click the button, nothing happens.

SimpleAdapter adapter;
List<HashMap<String, String>> painItems = new ArrayList<HashMap<String, String>>();
ListView listthings;
   ...

    cb = (CheckBox)findViewById(R.id.checkBox1);    
    adapter = new SimpleAdapter(this, painItems, R.layout.mylistlayout,
            from, to);
    listthings.setAdapter(adapter);
    listthings.setOnItemClickListener(this);

    deleteButton = (Button) findViewById(R.id.deleteButton);
    deleteButton.setOnClickListener(this);

 ...

public void onClick(View v) {

    if (v == this.deleteButton) {
//      Toast.makeText(this, "delete clicked", Toast.LENGTH_SHORT).show();
        deleteCheckedItems();
    }
}

...
 private void deleteCheckedItems() {
    int count = this.listthings.getAdapter().getCount();
    for (int i = 0; i < count; i++) {
        if (this.listthings.isItemChecked(i)) {
            painItems.remove(i);
            adapter.notifyDataSetChanged();
                            listthings.invalidateViews();
        }
    }

Any help appreciated. Thank You in advance.

Upvotes: 0

Views: 547

Answers (1)

Waza_Be
Waza_Be

Reputation: 39558

1) do not put adapter.notifyDataSetChanged(); into your loop but after deleteCheckedItems();

2) Why did you use: listthings.invalidateViews(); ? You can remove this line, this will redraw your list

3) why havn't you accepted my answer here: How to implement check box in listView Android to delete listItems

4) have you tested a toast after painItems.remove(i); that will show you if items are really removed? Or maybe just after calling deleteCheckedItems(), display the new painItems to see if everything worked

Upvotes: 1

Related Questions