0

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?

shaneburgess
  • 15,702
  • 15
  • 47
  • 66

1 Answers1

4

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 Conradt
  • 28,420
  • 21
  • 138
  • 192
  • I am using your answer here to search for Location but the `ProgressDialog' appears very briefly and is dismissed immediately (almost like a flash). I want it to remain showing until the Location is found. Please advise me on how to do this. – Emzor Jan 18 '16 at 17:43