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(); }
Just clone and open the project in Android Studio (gradle). This project has a MainAcitivity building a ListView with all random data. This list can be refreshed using the action menu.
This example demonstrates how do I dynamically update a ListView in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
To refresh the ListView in Android, call notifyDataSetChanged() method on the Adapter that has been set with the ListView. Also note that the method notifyDataSetChanged() has to be called on UI thread.
You can modify existing adapter data and call notifyDataSetChanged(). In your case you should call listView. setAdapter(adapter) in onClick method.
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.
In my understanding, if you want to refresh ListView immediately when data has changed, you should call notifyDataSetChanged()
in RunOnUiThread()
.
private void updateData() { List<Data> newData = getYourNewData(); mAdapter.setList(yourNewList); runOnUiThread(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); } }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With