I am wondering how I should implement a ListAdapter
that loads its views asynchronously into a ListView
? I want to do this because I am populating the list with information from my database, which is making my activity a bit slow to load at times.
You can use an AsyncTask
and use the onPostExecute
methods to publish the newly loaded results:
private ArrayAdapter adapter = new YourArrayAdapter();
private class YourAsyncTask extends AsyncTask<Void, Void, List<YourItem>> {
@Override
protected void onPreExecute() {
// start loading animation maybe?
adapter.clear(); // clear "old" entries (optional)
}
@Override
protected List<YourItem> doInBackground(Void... params) {
// everything in here gets executed in a separate thread
return DataBase.getItems();
}
@Override
protected void onPostExecute(List<YourItem> items) {
// stop the loading animation or something
adapter.addAll(items);
}
}
The best approach I've seen so far is from CommonsWare. It was found in this related answer.
public class AsyncDemo extends ListActivity {
private static final String[] items={"lorem", "ipsum", "dolor",
"sit", "amet", "consectetuer",
"adipiscing", "elit", "morbi",
"vel", "ligula", "vitae",
"arcu", "aliquet", "mollis",
"etiam", "vel", "erat",
"placerat", "ante",
"porttitor", "sodales",
"pellentesque", "augue",
"purus"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
new ArrayList<String>()));
new AddStringTask().execute();
}
class AddStringTask extends AsyncTask<Void, String, Void> {
@Override
protected Void doInBackground(Void... unused) {
for (String item : items) {
publishProgress(item);
SystemClock.sleep(200);
}
return(null);
}
@Override
protected void onProgressUpdate(String... item) {
((ArrayAdapter<String>)getListAdapter()).add(item[0]);
}
@Override
protected void onPostExecute(Void unused) {
Toast
.makeText(AsyncDemo.this, "Done!", Toast.LENGTH_SHORT)
.show();
}
}
}
The easiest thing is to use an AsyncTask to do the loading and call publishProgress
as each item is loaded (or, if you want to load all items and have them appear all at once, update the UI in onPostExecute
Is .notifyDataSetChanged() possibly what you're after? Each time you add a new item to the list that backs the ArrayAdapter, you can call .notifyDataSetChanged() on that adapter instance to tell it to refresh. This way your ListView can gradually build up and display each item as they're added to the list.
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