tags:

views:

19

answers:

1

In my activity I need a ProgressDialog with a horizontal progress bar to visualise the progress of a background task. To make the activity care for the dialog e.g. in case of screen rotation, I would like to use a managed dialog created in onCreateDialog. The problem is that I need to update the progress bar of the dialog after it has been created and therefor I need a reference to the managed progress dialog: Does anyone know how to retrieve a reference to a dialog created by onCreateDialog?

At the moment I am storing a reference to the dialog created in onCreateDialog, but that my fail with a InvalidArgumentException in the onFinished() method after the screen has been rotated (and the activity has been recreated):

public final class MyActivity extends Activity {
  private static final int DIALOG_PROGRESS = 0;
  private ProgressDialog progressDialog = null;

  // [...]

  @Override
  protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_PROGRESS:
      progressDialog = createProgressDialog();
      return progressDialog;
    default:
      return super.onCreateDialog(id);
    }
  }

  // [...]

  public void updateProgress(int progress) {
    progressDialog.setProgress(0);
  }

  public void onFinished() {
    progressDialog.dismiss();
  }

  // [...]
}

I would have expected something like a getDialog(int) method in the Activity class to get a reference to a managed dialog, but this doesn't seem to exist. Any ideas?

A: 

I answer myself:

  1. There really is no getDialog(int) method available in the Activity class.
  2. Storing the reference like shown above works correctly -- the bug was something else...

The problem was, that the parallel thread, that called the onFinished() method called this method on the already destroyed activity, thus the accessed ProgressDialog instance is still existing but no longer a valid dialog. Instead another activity with another ProgressDialog has already been created by Android.

So all I needed to do was to make the background thread call the onFinished() method of the new activity and everything works fine. To switch the reference I override the onRetainNonConfigurationInstance() and getLastNonConfigurationInstance() methods of the Activity class.

The good thing of the shown example: Android really cares about recreating the new dialog after the screen orientation changed. So constructing the ProgressDialog that way is definitely easier than using ProgressDialog.show() where I would need to handle the dialog recreation on my own (the two methods described above would be a good place to do this.

sven