views:

192

answers:

1

I am reading a few thousand items out of a database in my Android app and want to show a loading dialog, start a thread and read the database then close the dialog and then populate a listview with the data. I cant seem to figure this out.

I have the dialog pop up and disappear but I don't know how to populate the listview after the thread is done.

Any ideas?

+3  A: 

Use an AsyncTask, populate the listview in onPostExecute().

http://www.screaming-penguin.com/node/7746

private class InsertDataTask extends AsyncTask<Void, Void, Void> {

  private final ProgressDialog dialog = new ProgressDialog(Main.this);

  // can use UI thread here
  protected void onPreExecute() {
     this.dialog.setMessage("Inserting data...");
     this.dialog.show();
  }
  // automatically done on worker thread (separate from UI thread)
  protected Void doInBackground(final String... args) {
     //do something in background, i.e. loading data
     return null;
  }

  // can use UI thread here
  protected void onPostExecute(final Void unused) {
     if (this.dialog.isShowing()) {
        this.dialog.dismiss();
     }
     // populate list here
  }
}

...

new InsertDataTask ().execute();

Also helpful: http://developer.android.com/resources/articles/painless-threading.html

Mathias Lin