Paulo Rodrigues
Paulo Rodrigues

Reputation: 5303

ProgressDialog while load Activity

I found this code in SO to show ProgressDialog while load Activity:

progDailog = ProgressDialog.show(MyActivity.this, "Process", "please wait....", true, true);

new Thread(new Runnable() {
    public void run() {
        // code for load activity
}).start();

Handler progressHandler = new Handler() {
    public void handleMessage(Message msg1) {
        progDailog.dismiss();
    }
};

But I always get this exception:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

I appreciate any help for this issue, thanks in advance.

Upvotes: 2

Views: 6613

Answers (3)

Sambuca
Sambuca

Reputation: 1254

Here is what I would do,
AsyncTask to do the "heavy work" in background:

public class MyTask extends AsyncTask<String, String, String> {
  private Context context;
  private ProgressDialog progressDialog;

  public MyTask(Context context) {
    this.context = context;
  }

  @Override
  protected void onPreExecute() {
    progressDialog = new ProgressDialog(context);
    progressDialog.show();
  }

  @Override
  protected String doInBackground(String... params) {
    //Do your loading here
    return "finish";
  }

  @Override
  protected void onPostExecute(String result) {
    progressDialog.dismiss();
    //Start other Activity or do whatever you want
  }
}

Start the AsyncTask:

MyTask myTask = new MyTask(this);
myTask.execute("parameter");

Of course you can change the generic types of the AsyncTask to match your problems.

Upvotes: 6

Andro Selva
Andro Selva

Reputation: 54322

The problem is because you are trying to create Handler inside a worker Thread. It is not possible. Create your Handler inside of onCreate() or somewhere else on the main UI. And you can send message to your handler from your Worker Thread. This is because Android doesn't allow you to modify the UI from any other Thread other than the Main UI thread itself.

Upvotes: 1

lrAndroid
lrAndroid

Reputation: 2854

You need to create your handler on the main thread rather than inside OnClick.

Upvotes: 0

Related Questions