Java.lang.IllegalStateException (Can't complete this action after onSaveInstanceState)

I am getting this error with the following message in another scenario:

  • The actions were destroyed and
  • Can't take this action after onSaveInstanceState

I am writing an application in which Two Activities communicate with each other. Activity-A launches Activity-B with an Intent. This Activity-B class has two child fragments. Fragment-A uses the public activity method to start another fragment-B .

public void beginTransaction(ID id, Bundle bundle) {

        Fragment fragment = getFragmentItem(id);

        // In case this activity was started with special instructions from an Intent,
        // pass the Intent extras to the fragment as arguments
        fragment.setArguments(bundle);

        // Add the fragment to the 'fragment_container' FrameLayout
        fragmentManager.beginTransaction()
        .add(R.id.fragment_container, fragment).commitAllowingStateLoss();
    }

      

Fragment-B on every finish () call to kill Activity-B and then switch back to Activity-A again . And the same process is repeated. After getting 2-3 times, I get:

java.lang.IllegalStateException: Cannot execute this action after onSaveInstanceState E / AndroidRuntime (9008): at android.support.v4.app.FragmentManagerImpl.checkStateLoss (FragmentManager.java:1354) E / AndroidRuntime (9008): at android.support .v4.app.FragmentManagerImpl.enqueueAction (FragmentManager.java:1372)

so to avoid this I follow this StackOverflow question and it started giving me

Java.lang.IllegalStateException: Activity was destroyed E / AndroidRuntime (9235): at android.support.v4.app.FragmentManagerImpl.enqueueAction (FragmentManager.java:1376) E / AndroidRuntime (9235): at android.support.v4.app .BackStackRecord.commitInternal (BackStackRecord.java:595)

any suggestion that I am missing here.

GOT IT I got a solution. This is a bug in a transaction to add a fragment. I used .add to use .replace (as my requirement is not to maintain a stack) and use commitAllowTransaction to commit it. I read http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html and it looks like what I did might be costly, but for the fragment to work fine, the transaction works great.

+3


source to share


1 answer


How can I not comment on your question because of the lesser point of reputation. I am assuming this is your public method to modify a fragment.

public void beginTransaction(ID id, Bundle bundle)

      

In this method every time you add a fragment to an activity. So if you add the first snippet it will work fine, but in the case of the second snippet you should use replace not add



    fragmentManager.beginTransaction()
    .replace(R.id.fragment_container, fragment).commitAllowingStateLoss();

      

I think after that you shouldn't face this problem. or you can use 'replace' for the first and second chunks. I hope this helps you.

+13


source







All Articles