androidandroid-activityandroid-dialog

Android Dialog is showing again after Activity is re-created


I have an Activity and need to show Dialog in it. Everything works fine here. I've overrided onCreateDialog method in Activity, here is the code:

@Override
protected Dialog onCreateDialog(int dialog)
{
    if(dialog == 10)
    {
        if(waitDialog != null)
            waitDialog.dismiss();

        dialogCreated = true;
        waitDialog = CreateWaitDialog(this); 
        return waitDialog;
    }
    else
        return new Dialog(this);
}

Where CreateWaitDialog is custom method of creating a dialog and waitDialog is static variable.

I'm showing dialog by calling showDialog(10)

All code is executing fine.

After dialog has been shown, i'm closing it by calling.

if(waitDialog != null)
    waitDialog.hide();

And i'm dismissing it when Activity is destroyed.

if(dialogCreated)
        dismissDialog(10);
    super.onDestroy();

It's closing and everything is great. BUT, when I change the orientation of my device and Activity is recreated it pops up again by himself! I'm not calling any showDialog or something like that it is just popping up!


Solution

  • I think this is defined behavior of the Activity and onCreateDialog:

    Callback for creating dialogs that are managed (saved and restored) for you by the activity. The default implementation calls through to onCreateDialog(int) for compatibility. If you are targeting HONEYCOMB or later, consider instead using a DialogFragment instead.

    If you use showDialog(int), the activity will call through to this method the first time, and hang onto it thereafter. Any dialog that is created by this method will automatically be saved and restored for you, including whether it is showing.

    If you would like the activity to manage saving and restoring dialogs for you, you should override this method and handle any ids that are passed to showDialog(int).

    I will guess that onDestroy is too late in the activity lifecycle to dismiss the dialog. My guess is that the Activity is saving your dialog inside onSaveInstanceState.

    I might try dismissing the dialog inside onSaveInstanceState before calling super.onSaveInstanceState, then the dialog will be dismissed before android tries to save and restore it.

    @Override
    onSaveInstanceState(Bundle outstate) {
    
        dismissDialog(10);  
        super.onSaveInstanceState(outstate);
    }