Reputation: 619
I am not able to run a ProgressDialog
inside the doInBackground
method of AsyncTask. It gives me the following error:
ERROR/AndroidRuntime(12986): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
And the error is on this line in the code:
final ProgressDialog dialog = ProgressDialog.show(GalleryView.this, "Refresh", "Loading... please wait", true);
Any help much appreciated.
Upvotes: 0
Views: 1022
Reputation: 2929
ProgressDialog is UI code, so it must happen on the event queue. AsyncTask runs off the event queue. You can do a progress dialog as such:
ProgressBar progressBar = activity.findViewById(progressBarID);
progressBar.setIndeterminate(true)
progressBar.setVisibility(View.VISIBLE);
AsyncTask<Void, Void, Void> aTask = new AsyncTask<Void, Void, Void>(){
@Override
protected Void doInBackground(Void... arg0) {
//Do your operations here
return null;
}
@Override
protected void onPostExecute(Void result) {
progressBar.setVisibility(View.GONE);
//Wrap up anything here, like closing the popup.
}
};
aTask.execute((Void)null);
Upvotes: 1
Reputation: 6892
You can show the progressdialog in the onPreExecute method and dismiss it in the onPostExecute method. These two methods run in the UI thread. The doInBackGround method runs in another thread.
Another possibility is to just show the progressdialog before you start the AsyncTask. Personally I like the option to use onPreExecute and onPostExecute. The progressdialog is then linked nicely to the AsyncTask.
Upvotes: 3
Reputation: 81349
The AsyncTask
construct is about separating background and UI thread operations. Within doInBrackground
you are not in the UI thread, so you cannot do UI related logic at all. The right place to do that is in the methods that run on the UI thread. I'm guessing for your particular case such place would be onPreExecute
.
Upvotes: 1
Reputation: 1480
As the doinbackground doesn't run on the ui thread so it cannot create UI elements. You should create the progress dialog before executing the AsyncTask.
Upvotes: 1