Reputation: 3875
So, in my Dialog, I have a button which starts an Asynctask downloader to get some file from my server; and that works just fine. However, I want to dismiss my current Dialog and display the ProgressDialog on button clicked. How would I approach this problem?
At the moment, if I click on the button (an element inside my Dialog) the whole UI get froze while the downloader downloading the file from the server. Once the downloader finished its task then the progress dialog will then get shown.
My code looks something like this
MainActivity{
Dialog dialog;
ProgressDialog progress;
onCreate(){
dialog = new Dialog(this);
progress = new ProgressDialog(this);
dialog.setContentView(Some View Resource With My Button);
someMethod();
dialog.show();
}
someMethod(){
Button button = (Button) dialog.findViewById(resource of button);
button.setOnClickListener(new OnClickListener(){
onClick(){
dialog.dismiss();
progress.show();
new DownloaderAsyncTask(progress).execute().get();
}
//go to another activity when download finished
});
}
private class DownloaderAsyncTask extends AsyncTask<Void, Void, Void>{
ProgressDialog progress;
DownloaderAsyncTask(ProgressDialog progress){
this.progress = progress;
}
doInBackGround(){
//Downloading
}
onPostExecute(){
//Kill connection
this.progress.dismiss();
}
}
}
Thanks. Please let me know if you guys need any additional information.
Upvotes: 1
Views: 3016
Reputation: 75645
You UI thread is frozen because you called get()
. Do not do that. Instead launch your AsyncTask
and make your onPostExecute()
call method containing the code you wanted to be executed when download ended, like this (more/less):
someMethod() {
Button button = (Button) dialog.findViewById(resource of button);
button.setOnClickListener(new OnClickListener(){
onClick(){
dialog.dismiss();
progress.show();
new DownloaderAsyncTask().execute();
}
});
private void downloaderFinished() {
this.progress.dismiss();
/// go to next activity.
}
private class DownloaderAsyncTask extends AsyncTask<Void, Void, Void>{
doInBackGround(){
//Downloading
}
onPostExecute(){
//Kill connection
downloaderFinished();
}
}
That's how it shall be done as async
stands for, well, asynchronous so calling get()
kills all the benefits.
Upvotes: 2
Reputation: 48871
new DownloaderAsyncTask(progress).execute().get();
I really have no idea why AsyncTask
has the get()
method - it basically turns the asynchronous process into a synchronous one because it will block and wait for a result. That's the reason the UI freezes.
If you want to wait for the downloader to finish and then do something else, that's what onPostExecute(...)
is for.
Upvotes: 6