Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how to refresh ListView contents?

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(); } 
like image 518
ab11 Avatar asked Feb 04 '11 23:02

ab11


People also ask

How do you refresh a ListView?

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.

How to update ListView item in Android?

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.

How to Refresh ListView in Kotlin?

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.

How do I refresh Arrayadapter?

You can modify existing adapter data and call notifyDataSetChanged(). In your case you should call listView. setAdapter(adapter) in onClick method.


2 Answers

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.

like image 103
LoneDuck Avatar answered Sep 20 '22 16:09

LoneDuck


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();         }     }); } 
like image 42
khcpietro Avatar answered Sep 17 '22 16:09

khcpietro