ProgressDialog in AsyncTask: Dynamic Update max()
1 min read

ProgressDialog in AsyncTask: Dynamic Update max()

ProgressDialog in AsyncTask: Dynamic Update max()

Sometimes you determine the max of the progress bar in the background task. Unfortunately, there's almost no way to transmit that to an UI thread-executed method like onProgressUpdate() (well, you could, but that'd be abusing the method). Instead you can do something like:

public class MyTask extends AsyncTask<Params, Progress, Result> {
    private ProgressDialog progressDialog;
    int max;
    int offset;

    @Override
    protected Void doInBackground(Params... params) {
        this.max = calculate_max();
        this.offset = 0;
        for (int i=0; i<this.max; i++) {
            // ...
            publishProgress(new Progress());
            // ...
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Result... values) {
        super.onProgressUpdate(values);
        this.progressDialog.setMessage(values[0].label);
        this.progressDialog.setProgress(
            calculateProgressPercent(this.offset, this.max)
        );
        this.offset ++;
    }

    private int calculateProgressPercent(int done, int max) {
        done = done * 100;
        return done / max;
    }

}

This way, the variables are updated in their own thread and the progress is advanced with a percentage.