0

Here is my code for Progress Dialog in Android and i am getting following error:android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. I saw all previous post related to this error but i could not correct this error.

// Waiting screen 
    pleaseWaitdialog = ProgressDialog.show(PhoneBookListView.this, "Loading", "Please wait...", true);
            new Thread(new Runnable() {
                  @Override
                  public void run()
                  {
                    Looper.prepare();
                    // do the thing that takes a long time
                    LoadContactFromPhoneAndSim();
                    PhoneBookListView.this.runOnUiThread(new Runnable() {
                      @Override
                      public void run()
                      {
                          pleaseWaitdialog.dismiss();
                      }
                    });
                  }
                }).start();

Any help will be appreciate Thanks.

Pawan Chaurasiya
  • 881
  • 2
  • 16
  • 30

1 Answers1

2

I suggest you use an AsyncTask, as they make this sort of thing easier. In general, you want to do complex stuff on a background thread, and only update the UI from the UI thread.

public class PhonebookLoader extends AsyncTask<Void,Void,Void> {

protected Void doInBackground(Void ... params) {
    LoadContactFromPhoneAndSim();
    return void;
}

protected void onPostExecute(Void param) {
    pleaseWaitdialog.dismiss();
}
}

To start it with this class, you just call this:

new PhonebookLoader.execute();

And you can do all kinds of things with this, like publish your progress so the user knows how far they have progressed, update the UI thread after you are done loading, etc. AsyncTask is your friend, use it.

Looking at this, I suspect that PhonebookLoader is probably both loading the data and putting it on the UI. Separating these two tasks will make your app much more responsive and easier to maintain.

PearsonArtPhoto
  • 38,970
  • 17
  • 111
  • 142