how to populate a listview asynchronously?
Asked Answered
S

6

17

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.

Sikata answered 11/5, 2011 at 17:7 Comment(0)
S
21

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);
    }
}
Scramble answered 11/5, 2011 at 17:24 Comment(1)
thank you! will try this when i get back to work tomorrow :) had not thought of doing it this waySolnit
M
5

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();
    }
  }
}
Margaux answered 20/8, 2012 at 14:41 Comment(0)
R
3

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

Rankle answered 11/5, 2011 at 17:11 Comment(0)
C
1

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.

Circumstantial answered 11/5, 2011 at 17:19 Comment(0)
I
0

Use AsyncTask. That can help you to retrieve your data in background.

Illumination answered 11/5, 2011 at 17:9 Comment(1)
I use AsyncTasks frequently, but how do i implement it into a listadapter? I am trying to create a list where a view is shown when it is done loading. Using a asynctask to set a listadapter will load the whole list in the background and then show the information. i am looking for an implementation that loads one list item at a time and show it in the list.Solnit
H
0

With Kotlin and the Kotlin extension libraries, this task has gotten way easier. You can use the doAsync/uiThread construct in a library called Anko with a fraction of the code. In the link tutorial below I use this library to populate a ListView with stock quotes calling a REST API Asynchronously with Kotlin. Kotlin is fully integrated into Android Studio:

http://www.todroid.com/creating-a-stock-pricing-application-with-kotlin-for-android/

Historic answered 17/11, 2017 at 3:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.