76

I have a LoginActivity (User Logs in). It is basically its own Activity that is themed like a dialog (to appear as if a dialog). It appears over a SherlockFragmentActivity. What I want is: If there is a successful login, there should be two FragmentTransaction's to update the view. Here is the code:

In LoginActivity, if successful login,

setResult(1, new Intent());

In SherlockFragmentActivity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == 1) {
        LoggedStatus = PrefActivity.getUserLoggedInStatus(this);
        FragmentTransaction t = MainFragmentActivity.this.getSupportFragmentManager().beginTransaction();
        SherlockListFragment mFrag = new MasterFragment();
        t.replace(R.id.menu_frame, mFrag);
        t.commit();

        // Set up Main Screen
        FragmentTransaction t2 = MainFragmentActivity.this.getSupportFragmentManager().beginTransaction();
        SherlockListFragment mainFrag = new FeaturedFragment();
        t2.replace(R.id.main_frag, mainFrag);
        t2.commit();
    }
}

It crashes on the first commit, with this LogCat:

E/AndroidRuntime(32072): Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
E/AndroidRuntime(32072):    at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1299)
E/AndroidRuntime(32072):    at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1310)
E/AndroidRuntime(32072):    at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:541)
E/AndroidRuntime(32072):    at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:525)
E/AndroidRuntime(32072):    at com.kickinglettuce.rate_this.MainFragmentActivity.onActivityResult(MainFragmentActivity.java:243)
E/AndroidRuntime(32072):    at android.app.Activity.dispatchActivityResult(Activity.java:5293)
E/AndroidRuntime(32072):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3315)
1
  • how did you call startActivityForResult()
    – Rohit
    Sep 12, 2018 at 6:32

5 Answers 5

300

First of all, you should read my blog post for more information (it talks about why this exception happens and what you can do to prevent it).

Calling commitAllowingStateLoss() is more of a hack than a fix. State loss is bad and should be avoided at all costs. At the time that onActivityResult() is called, the activity/fragment's state may not yet have been restored, and therefore any transactions that happen during this time will be lost as a result. This is a very important bug which must be addressed! (Note that the bug only happens when your Activity is coming back after having been killed by the system... which, depending on how much memory the device has, can sometimes be rare... so this sort of bug is not something that is very easy to catch while testing).

Try moving your transactions into onPostResume() instead (note that onPostResume() is always called after onResume() and onResume() is always called after onActivityResult()):

private boolean mReturningWithResult = false;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    mReturningWithResult = true;
}

@Override
protected void onPostResume() {
    super.onPostResume();
    if (mReturningWithResult) {
        // Commit your transactions here.
    }
    // Reset the boolean flag back to false for next time.
    mReturningWithResult = false;
}

This might seem a little weird, but doing this sort of thing is necessary to ensure that your FragmentTransactions are always committed after the Activity's state has been restored to its original state (onPostResume() is guaranteed to be called after the Activity's state has been restored).

24
  • 4
    In Fragments, I'm using onResume in the absence of onPostResume. I haven't seen the issue again, but perhaps you want to comment on this. PS. Thanks a lot for your insightful posts!
    – Maragues
    Sep 18, 2013 at 14:17
  • 27
    Yes, doing this in Fragment#onResume() is fine. This is because FragmentActivity#onPostResume() calls FragmentActivity#onResumeFragments(), which calls FragmentManager#dispatchResume(), which calls Fragment#onResume() for each of the activity's fragments. Therefore, Fragment#onResume() is called after FragmentActivity#onPostResume() so there won't be a problem (you can check out the [source code](goo.gl/Lo1Z1T ) for each respective class to verify this for yourself... or you can just just me :P). And thanks! Glad you thought they were insightful. :) Sep 18, 2013 at 21:13
  • 1
    @Alex, If the dialogfragment makes a network call, and the Home button is pressed before the dialogfragment gets the async response, invoking this.dismiss() within the async response will cause a state loss exception. In this scenario, when should dismiss() be invoked so that there is no state loss? Note that request and response are within the dialogfragment, not within the activity. Oct 29, 2013 at 7:08
  • 2
    @crazyhorse In that case, it might be a good idea to cancel the async task and/or raise a flag to ensure that dismiss() isn't called inside AsyncTask#onPostExecute() (the dialog will be dismissed automatically by the FragmentManager in the case that the activity goes in the background, so there's no need for you to dismiss the dialog yourself after the activity has gone away anyway). Dec 19, 2013 at 4:53
  • 1
    Did not know about onPostResume(). Fixed my problem (I was creating a dialog fragment in onResume() after cancelling a system dialog from a pending intent, which crashed my app). Mar 25, 2015 at 10:52
1

This is similar to the @Alex Lockwood answer but using a Runnable:

private Runnable mOnActivityResultTask;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    mOnActivityResultTask = new Runnable() {
        @Override
        public void run() {
            // Your code here
        }
    }
}

@Override
protected void onPostResume() {
    super.onPostResume();
    if (mOnActivityResultTask != null) {
        mOnActivityResultTask.run();
        mOnActivityResultTask = null;
    }
}

In case you're running Android 3.0 and above with lambdas, use this:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    mOnActivityResultTask = () -> {
        // Your code here
    }
}
1
  • I'd rather go with runnable, since that lets you write the logic close to where it happens. In my case it's coming from rx subscriber.
    – Fabio
    Sep 23, 2017 at 7:35
-1

You can use ft.commitAllowingStateLoss() to solve this problem.

Reason: your ft.commit() method was toggled after onSaveInstanceState.

-1

your logcat clearly says: "Can not perform this action after onSaveInstanceState" -- your Activity is already dead at that point and could not return any results.

just move:

Intent in = new Intent();
setResult(1, in);

to the place in your Activity where it's still alive, and everything will be fine. and don't forget to finish() your Activity to deliver the result.

2
  • Thanks. finish() is last thing I am doing. I had the intent code just above it., I moved it up top and same error. I am adding code to answer... Apr 28, 2013 at 17:58
  • One more point on last comment. I actually don't see toast. But when I reenter app after crash I am logged in. Apr 28, 2013 at 18:03
-1

In my Case I faced the same issues Because of the Following

public void onBackPressed() {
    super.onBackPressed();
    setIntents();

}


private void setIntents(){
    Intent searchConstaints=new Intent();
    searchConstaints.putExtra("min",20);
    searchConstaints.putExtra("max",80);
    setResult(101,searchConstaints);
    finish();
}

Solved by re-arranging the function Calls within onBackPressed()

public void onBackPressed() {

    setIntents();
    super.onBackPressed();

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.