Android: how to refresh ListView contents?

ab11 picture ab11 · Feb 5, 2011 · Viewed 138.6k times · Source

My ListView is using an extension of BaseAdapter, I can not get it to refresh properly. When I refresh, it appears that the old data draws on top of the new data, until a scroll event happens. The old rows draw on top of the new rows, but the old rows disappear when I start scrolling.

I have tried calling invalidateViews(), notifyDataSetChanged(), and notifyDataSetInvalidated(). My code looks something like:

private void updateData()
{
   List<DataItems> newList = getNewList();

   MyAdapter adapter = new MyAdapter(getContext());
   //my adapter holds an internal list of DataItems
   adapter.setList(newList);
   mList.setAdapter(adapter);
   adapter.notifyDataSetChanged();
   mList.invalidateViews();
}

Answer

LoneDuck picture LoneDuck · Sep 30, 2012

To those still having problems, I solved it this way:

List<Item> newItems = databaseHandler.getItems();
ListArrayAdapter.clear();
ListArrayAdapter.addAll(newItems);
ListArrayAdapter.notifyDataSetChanged();
databaseHandler.close();

I first cleared the data from the adapter, then added the new collection of items, and only then set notifyDataSetChanged(); This was not clear for me at first, so I wanted to point this out. Take note that without calling notifyDataSetChanged() the view won't be updated.