Updating progress dialog in Activity from AsyncTask

39,907

Solution 1

AsyncTask has method onProgressUpdate(Integer...) that you can call each iteration for example or each time a progress is done during doInBackground() by calling publishProgress().

Refer to the docs for more details

Solution 2

you can update from AsyncTask's method onProgressUpdate(YOUR_PROGRESS) that can be invoked from doInBackground method by calling publishProgress(YOUR_PROGRESS) the data type of YOUR_PROGRESS can be defined from AsyncTask<Int, YOUR_PROGRESS_DATA_TYPE, Long>

Share:
39,907
Laimoncijus
Author by

Laimoncijus

Updated on July 09, 2022

Comments

  • Laimoncijus
    Laimoncijus almost 2 years

    In my app I am doing some intense work in AsyncTask as suggested by Android tutorials and showing a ProgressDialog in my main my activity:

    dialog = ProgressDialog.show(MyActivity.this, "title", "text");
    new MyTask().execute(request);
    

    where then later in MyTask I post results back to activity:

    class MyTask extends AsyncTask<Request, Void, Result> {
    
        @Override protected Result doInBackground(Request... params) {
            // do some intense work here and return result
        }
    
        @Override protected void onPostExecute(Result res) {
            postResult(res);
        }
    }
    

    and on result posting, in main activity I hide the dialog:

    protected void postResult( Result res ) {
        dialog.dismiss();
        // do something more here with result...
    }
    

    So everything is working fine here, but I would like to somehow to update the progress dialog to able to show the user some real progress instead just of dummy "Please wait..." message. Can I somehow access the progress dialog from MyTask.doInBackground, where all work is done?

    As I understand it is running as separate Thread, so I cannot "talk" to main activity from there and that is why I use onPostExecute to push the result back to it. But the problem is that onPostExecute is called only when all work is already done and I would like to update progress the dialog in the middle of doing something.

    Any tips how to do this?