Pim Reijersen
Pim Reijersen

Reputation: 1133

Background operation and ProgressDialog

I created an AsyncTask to perform my background operation. The UI shows a ProgressDialog. I pass the Context to the constructor of the AsyncTask.

When I want to manipulate the the ProgressDialog text from AsyncTask it errors because the ProgressDialog box is created by a different thread.

Tips or ideas on how I can make the AsyncTask communicate with the ProgressDialog box, or a better way to create the ProgressDialog box?

Upvotes: 0

Views: 277

Answers (2)

inazaruk
inazaruk

Reputation: 74780

You shouldn't communicate with UI from AsyncTask's doInBackground function. Use onProgressUpdate function instead.

private class BackgrounTask extends AsyncTask<Integer, Integer, Integer> {

    protected Integer doInBackground(Integer... count){
       int max = count[0];
       for (int i = 0; i < count; i++) {
         publishProgress(i, max);
       }
       return max;
    }

    protected void onProgressUpdate(Integer... progress) {
       int cur = progress[0];
       int max = progress[1];

       //update your progress dialog here
    }

    protected void onPostExecute(Integer result) {
       //process result
    }
}

Upvotes: 1

Michael
Michael

Reputation: 54705

Use AsyncTask.publishProgress() method and override AsyncTask.onProgressUpdate() method. In this method update your progress dialog.

Upvotes: 0

Related Questions