I have asynktask that shows a progressDialog and update its value in doInBackground method. the methods code:
@Override
protected void onPreExecute() {
progress = new ProgressDialog(cont);
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.setTitle(cont.getResources().getString(R.string.pleaseWait));
progress.setMessage(cont.getResources().getString(R.string.loadingImages));
progress.show();
super.onPreExecute();
}
@Override
protected String doInBackground(Void... arg0) {
progress.setProgress(2);
//do some work on the database and network
progress.setProgress(25);
//Do some extra work
for(int i = 0; i < itemImagesList.size(); i++){
publishProgress((int) ((i / (float) itemImagesList.size()) * 100));
//Do somework
}
}
@Override
protected void onProgressUpdate(Integer... prog) {
progress.setProgress(prog[0]);
}
@Override
protected void onPostExecute(String result) {
progress.dismiss();
super.onPostExecute(result);
}
The progressDialog value doesn't change at all! and if I tried to set the dialog message using:
progress.setMessage("At item "+i);
some exception occurs if I put it in the middle of the method, but in the first it works fine!
what's wrong?
ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar , which can be embedded in your app's UI. Alternatively, you can use a notification to inform the user of the task's progress.
ProgressDialog 's look can be replicated by placing a ProgressBar into an AlertDialog . You can still use it, but Android does not want you to use it, that is why it is deprecated.
Your issue is related to setIndeterminate(true);
You should set it to false
if you want to have progress update (take a look at Android setProgress doc), don't forget to also use setMax()
to set progress max value to the desired one.
And as said Laurent you can change progress only on UI thread so you have to do it in onProgressUpdate
and not in doInBackground
You have to update progress value inside UI thread so in method onProgressUpdate of your AsyncTasK
Do it like this
@Override
protected String doInBackground(Void... arg0) {
getActivity ().runOnUiThread (new Runnable() {
@Override
public void run () {
progress.setProgress(2);
//do some work on the database and network
progress.setProgress(25);
}
});
//Do some extra work
for(int i = 0; i < itemImagesList.size(); i++){
publishProgress((int) ((i / (float) itemImagesList.size()) * 100));
//Do somework
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With