satorikomeiji
satorikomeiji

Reputation: 469

DialogFragment lifecycle behavior

I have a custom DialogFragment which overrides onDismiss() method:

@Override
public void onDismiss(DialogInterface dialog) {
    ((MyActivity) getActivity()).onDismiss();
    super.onDismiss(dialog);
} 

The problem is that this method could be executed just after onDetach(), which in turn would trigger a NullPointerException. Is there a way to safely detect a dialog dismissal before it's detached?

Upvotes: 0

Views: 3240

Answers (1)

Bob Snyder
Bob Snyder

Reputation: 38319

I dismissed a dialog hosted in a DialogFragment by: (1) calling Dialog.dismiss(), (2) touching outside the dialog, and (3) pressing Back. In each case, when onDismiss() was called, getActivity() was not null (i.e. the fragment was attached). The only time when onDismiss() was called when the fragment was not attached was during a restart caused by a configuration change. In this case, onDismiss() was called for the old fragment that was being destroyed. For this situation, you do not need to notify your activity that the dialog is dismissed, because the dialog is recreated as a result of the restart processing. In my opinion, the code you posted, with an added check, is an acceptable and safe way to handle dialog dismiss events:

@Override
public void onDismiss(DialogInterface dialog) {
    if (getActivity() != null) {
        ((MyActivity) getActivity()).onDismiss();
    }
    super.onDismiss(dialog);
}

Upvotes: 1

Related Questions