问题
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?
回答1:
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
回答2:
You have to update progress value inside UI thread so in method onProgressUpdate of your AsyncTasK
回答3:
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
}
}
来源:https://stackoverflow.com/questions/28983419/progressdialog-setprogress-and-setmessage-inside-asynctask-dont-work