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?
I answer myself:
getDialog(int)method available in theActivityclass.The problem was, that the parallel thread, that called the
onFinished()method called this method on the already destroyed activity, thus the accessedProgressDialoginstance is still existing but no longer a valid dialog. Instead another activity with anotherProgressDialoghas 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 theonRetainNonConfigurationInstance()andgetLastNonConfigurationInstance()methods of theActivityclass.The good thing of the shown example: Android really cares about recreating the new dialog after the screen orientation changed. So constructing the
ProgressDialogthat way is definitely easier than usingProgressDialog.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.