Reputation: 385
In an Asyntask, i instantiate a progress Dialog in global variables of Asyntask:
ProgressDialog progressDialog;
Then, in DoInBackGround, i call "publishProgress", so onProgressUpdate in called. There, in onProgressUpdate, i have the following code:
this.progressDialog=new ProgressDialog(mActivity);
this.progressDialog.setCancelable(true);
this.progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
this.progressDialog.setTitle("Iniciando la comunicación");
this.progressDialog.show();
I don´t know why, the progressDialog is never shown. I have tried using Toast with the same context, and it works fine. Although progressDialog not.
---------UPDATE--------------
Finally, I've figure it out using notifications.
Upvotes: 1
Views: 452
Reputation: 60913
Organize your AsyncTask
like this
private class YourTask extends AsyncTask<String, String, String> {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
...
// show the dialog
this.progressDialog=new ProgressDialog(mActivity);
this.progressDialog.setCancelable(true);
this.progressDialog.setProgressStyle(ProgressDialog. STYLE_HORIZONTAL);
//this.progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
this.progressDialog.setTitle("Iniciando la comunicación");
this.progressDialog.show();
}
@Override
protected String doInBackground(String... urls) {
...
publishProgress("" + progress);
...
}
protected void onProgressUpdate(String... progress) {
progressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String result) {
// dismiss the dialog
progressDialog.dismiss();
...
}
}
Also you want to public the progress when the AsyncTask
is running, so you need a STYLE_HORIZONTAL
ProgressBar
not STYLE_SPINNER
ProgressBar
Hope this help
Upvotes: 4
Reputation: 27211
I saw this problem two years ago. There is something unpredictable behaviour while main UI thread interaction.
The solution I found is to use Thread
instead of AsyncTack
.
A quick simple example:
new Thread(new Runnable() {
public void run() {
//background code to calculate
//for example
for(int i = 0; i < 100000000L; i++){
myHugeCalc(i);
final int prog = i;
runOnUiThread(new Runnable() {
public void run() {
pbtext.setText("My progress: " + prog);
}
});
}
}).start();
Upvotes: 1
Reputation: 1304
There is another way to do so...
when you are calling this sync process from your class, start showing the progress dialog there, and onPostExecute
cancel it.
It will do your work...
but the best practise is to do it in onPreExecute
Upvotes: 0