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);
}
}