I need to populate a long ListView with data from the network, say 2-3 seconds for the entire data collection.  I don't want the user to see a loading Dialog and wait for the entire list download.  Instead I want to update the ListView as each item becomes available.  
ArrayAdapter from an AsyncTask with OnProgressUpdate?notifyDatasetChanged() after each added row?Fragment/Loader approach better?It's not important that the data be fetched entirely before the Activity dies (ie Service is unnecessary)
The best approach I've seen so far is from CommonsWare. It was found in this related answer.
Apparently there is nothing wrong with calling add without notifyDatasetChanged(). 
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();
    }
  }
}
                        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