1

I show a DialogFragment inside a button onClick event like below:

public void  onButtonClick() {
    myDialogFragment.show(getSupportFragmentManager(), "dialog");
}

Why does it cause IllegalStateException, may it called after onSaveInstanceState? Here is the log:

Fatal Exception: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
   at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1377)
   at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1395)
   at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:637)
   at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:616)
   at android.support.v4.app.DialogFragment.show(DialogFragment.java:139)
   at com.a.b.AFragment.editSex(AFragment.java:226)
   at com.a.b.AFragment.access$200(AFragment.java:46)
   at com.a.b.AFragment$3.onButtonClick(AFragment.java:134)
方人也
  • 151
  • 3
  • 10
  • take a look at this http://stackoverflow.com/questions/22713002/java-lang-illegalstateexception-can-not-perform-this-action-after-onsaveinstanc – Mehmet K Jun 29 '16 at 09:35
  • Post some code with logcat – Chandrakanth Jun 29 '16 at 09:35
  • Please read this http://stackoverflow.com/help/how-to-ask – Chandrakanth Jun 29 '16 at 09:47
  • I have looked at this link http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html, But I think the method will not be called after onSaveInstanceState – 方人也 Jun 29 '16 at 09:49
  • @Chandrakanth,thank you a lot, I have followed your suggestion. – 方人也 Jun 29 '16 at 09:55
  • Make sure you call through to super wherever appropriate. That includes `onResume`, `onStart`, `onCreate`, `onActivityCreate`, `onSaveInstanceState`, `onActivityResult` etc. That goes for fragments and for activities. – Eugen Pechanec Jun 29 '16 at 10:46

1 Answers1

1

Inside your show method call this

fragmentTransaction.commitAllowingStateLoss()

after adding fragment to

fragmentTransaction.add();

For reference

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.

Aman Jain
  • 2,975
  • 1
  • 20
  • 35
  • sometimes it can be a good choice (of course not all the time) but you need to put this on manifest at the activity where is the fragment --> android:configChanges="orientation|screenSize|layoutDirection" (in my case worked) – Cristian Babarusi May 08 '19 at 06:59