Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    mAlertDlg.dismiss();

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.

like image 814
Wayne Avatar asked May 30 '13 17:05

Wayne


2 Answers

If you want to dismiss a DialogFragment in onStop(), you probably don't want to use a DialogFragment but a classic Dialog instead.

The reason why DialogFragment exists is to allow a dialog to be restored automatically when the Activity is re-created. If you dismiss it in onStop(), it will never be restored.

Also, if you use dismissAllowingStateLoss(), the dismiss transaction may not be recorded properly in onSaveInstanceState() (as the name says, a state loss may occur), and this will result in the dialog being restored when the activity is re-created, and obviously that's not what you want.

like image 153
BladeCoder Avatar answered Oct 12 '22 20:10

BladeCoder


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.

like image 40
Nicolas Jafelle Avatar answered Oct 12 '22 21:10

Nicolas Jafelle