Reputation: 1
I am developing my first Androïd application and I'm facing a problem when I want to display a ProgressDialog to indicate that a process is being run. In my application, the user triggers a time consuming task by pressing a Button. The "OnClick" function of my "OnClickListener" is called when the user presses the Button. In this function, here is what I'm currently doing :
- creation and configuration of an instance of the ProgressDialog class,
- creation of a thread dedicated to the time consuming task,
- attempt to display the ProgressDialog using the "show" method,
- start of the thread,
- main Activity suspended (call of the "wait" function)
- wake up of the main Activity by the thread when it is finished
- removal of the ProgressDialog by calling the "dismiss" function.
Everything works fine (the result of the long task is correct) but the ProgressDialog nevers appears. What am I doing wrong?
Thanks in advance for the time you will spend trying to help me.
Upvotes: 0
Views: 1038
Reputation: 3593
I would suggest using AsyncTask
, as it's purpose is exactly to handle this kind of problem. See here for instructions how to use it. Note that the linked page in Floern's answer also recommends the use of AsyncTask
.
You would need to do the following:
AsyncTask
onPreExecute()
method to create and show a ProgressDialog
. (You could hold a reference to it in a member of your subclass)doInBackground()
method to execute your time consuming action.onPostExecute()
method to hide your dialog.execute()
on it.If you make your subclass an inner class of your activity, you can even use all of your activity's members.
Upvotes: 0
Reputation: 33904
You should not call wait()
to the Main Activity/UI thread, because this is actually freezing the UI including your ProgressDialog, so it has no time to fade in and will never be shown.
Try to use multithreading correctly: http://developer.android.com/resources/articles/painless-threading.html
final Handler transThreadHandler = new Handler();
public void onClick(View v) {
// show ProgressDialog...
new Thread(){
public void run(){
// your second thread
doLargeStuffHere();
transThreadHandler.post(new Runnable(){public void run(){
// back in UI thread
// close ProgressDialog...
}});
}
}.start();
}
Upvotes: 2