thedeepfield
thedeepfield

Reputation: 6196

ANDROID: Listview wont update after deleting database data

New to Android and I'm having an issue with updating my a ListView after deleting entries from a database.

In my activity I have a ListView with multiple choice checkboxes in each row. After the user presses a delete button, deleteName() gets called. deleteName() will then delete any Names that were checked in the ListView. The Names get deleted from the database, but the ListView never update.

I tried using adapter.notifyDataSetChanged() but nothing happens. Why wont my ListView update?

public void deleteName() {

    NamesDataSource datasource = new NamesDataSource(this);
    datasource.open();

    ListView listView = (ListView) findViewById(android.R.id.namelist);
    SparseBooleanArray checked = listView.getCheckedItemPositions();

    List<Name> values = datasource.getAllNames();
    ArrayAdapter<Name> adapter = new ArrayAdapter<Name>(this, android.R.layout.simple_list_item_multiple_choice, values);

    for (int i = 0; i < checked.size(); i++) {
        int position = checked.keyAt(i);
        if (checked.valueAt(i))
            datasource.deleteName(adapter.getItem(position));
    }

    adapter.notifyDataSetChanged();
    setListAdapter(adapter);
    datasource.close();

}

Upvotes: 0

Views: 909

Answers (3)

Kuffs
Kuffs

Reputation: 35661

Your code is not optimal as you are creating a new adapter with each call to the delete method. You should maintain an activity wide reference to the adapter (possibly in your 'OnCreate')

The reason your listview is not updating is because you are filling its adapter with values but not removing the deleted ones from it.

e.g you are

datasource.deleteName(adapter.getItem(position));

but there is no corresponding

adapter.remove(name);

Upvotes: 1

Abhinav Singh Maurya
Abhinav Singh Maurya

Reputation: 3313

That is happening because you are adding values to adapter before clearing database

add values to adapter after clearing/deleting values in database and then call adapter.notifyDataSetChanged();

Let me know if this helps you

Upvotes: 0

R9J
R9J

Reputation: 6715

Try this

listView.inValidate():

Upvotes: 0

Related Questions