0

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?

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
satorikomeiji
  • 469
  • 6
  • 16
  • Have you actually observed `onDismiss()` being invoked after the `DialogFragment` is detached? There are multiple other SO answers, such as [this one](http://stackoverflow.com/questions/23786033/dialogfragment-and-ondismiss), which use code similar to yours that users seem to be happy with, judging from the up-votes. – Bob Snyder Jan 28 '16 at 17:25
  • Are you seeing the problem when the configuration changes and the app restarts? – Bob Snyder Jan 28 '16 at 21:20
  • @qbix, I observed it when I tried to launch an activity calling the dismiss method right after that. It just seems to be detaching faster than calling `onDismiss()`, sometimes it's the opposite, though. – satorikomeiji Jan 29 '16 at 04:41

1 Answers1

1

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);
}
Bob Snyder
  • 37,759
  • 6
  • 111
  • 158
  • Thanks, in the end I came up with something similar, but it wasn't critical for my app. There could be a situation where `MyActivity.onDismiss()` should be called whenever a dialog is dismissed to obtain and store information about current stack of fragments or something similar. – satorikomeiji Jan 29 '16 at 04:48