Updating progress dialog in Activity from AsyncTask
Asked Answered
H

2

21

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?

Heft answered 4/1, 2011 at 8:48 Comment(0)
P
43

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

Ponceau answered 4/1, 2011 at 8:52 Comment(0)
H
1

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>

Hylo answered 27/2, 2019 at 11:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.