Wayne Wayne - 6 months ago 82
Android Question

How to safely dismiss DialogFragment in onstop()?

I need to dismiss DialogFragment in onStop() of an FragmentActivity if it is showing, this is what I did

if(mAlertDlg != null && mAlertDlg.getDialog() != null)

But I usually got IllegalStateException. So please tell me why that code is wrong and what is the correct way to dismiss DialogFragment in onStop()? Thank you.


You should use dialogFragment.dismissAllowingStateLoss(). As the documentation say for commitAllowingStateLoss():

"Like commit() but allows the commit to be executed after an activity's state is saved. This is dangerous because the commit can be lost if the activity needs to later be restored from its state, so this should only be used for cases where it is okay for the UI state to change unexpectedly on the user."

So for dismissAllowingStateLoss() is the same approach.