Search code examples
androidandroid-dialogfragment

android - dialogfragment using commitAllowStateLoss


What are the effects of commiting a dialogfragment transaction with state loss in android: Since its just a simple error dialog im showing with an ok button to close it i dont think i need to worry about state loss.

in my DialogFragment subclass i've over rided the show class so that it commits to include state loss so that i dont get illegalstateException...

 @Override 
  public void show(FragmentManager manager, String tag) {
      FragmentTransaction ft = manager.beginTransaction();
      ft.add(this, tag);
      //its just dialogs so  can we allow state loss to not trigger illegalStateExceptions
      ft.commitAllowingStateLoss();
  }

Solution

  • According to this Article Originally you are trying to avoid this error (Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState).

    This error stems from the fact that these Bundle objects of the onSaveInstanceState() represent a snapshot of an Activity at the moment onSaveInstanceState() was called, and nothing more. That means when you call FragmentTransaction#commit() after onSaveInstanceState() is called, the transaction won't be remembered because it was never recorded as part of the Activity's state in the first place

    You tried to work around that by using commitAllowingStateLoss(), let's discuss the difference between calling commit() and commitAllowingStateLoss() is that the latter will not throw an exception if state loss occurs. Usually you don't want to use this method because it implies that there is a possibility that state loss could happen. The better solution, of course, is to write your application so that commit() is guaranteed to be called before the activity's state has been saved, as this will result in a better user experience. Unless the possibility of state loss can't be avoided, commitAllowingStateLoss() should not be used.