1

I've got this code in a fragment:

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        if (requestCode == READ_REQUEST && resultCode == Activity.RESULT_OK) {
            Uri uri;
            if (resultData != null) {
                uri = resultData.getData();
                getChildFragmentManager().beginTransaction().add(new MyFragment(), TAG).commit();
            }
        }
    }

However there is crash with IllegalStateException. The activity can't create/restore transactions after onSaveInstanceState(). What is the correct method to start a fragment from another one in onActivityResult()?

Logcat:

03-17 18:55:37.372 26127 26127 E AndroidRuntime: Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1434)
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1452)
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    at android.app.BackStackRecord.commitInternal(BackStackRecord.java:708)
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    at android.app.BackStackRecord.commit(BackStackRecord.java:672)
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    at com.xxxx.ttyy.ui.SettingsFragment.onActivityResult(Unknown Source)
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    at android.app.Activity.dispatchActivityResult(Activity.java:6956)
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    ... 9 more
03-17 18:55:37.377   878  3186 W ActivityManager:   Force finishing activity com.balda.intenttask/.ui.MainActivity
greywolf82
  • 21,813
  • 18
  • 54
  • 108

1 Answers1

0

You can use commitAllowingStateLoss

From the Documentation:

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.

try using this:

getChildFragmentManager().beginTransaction().add(new MyFragment(), TAG).commitAllowingStateLoss();
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
  • Depends...it works in my case...so i would not call it just a `workaround`..see the Answer [Here](http://stackoverflow.com/questions/17184653/commitallowingstateloss-in-fragment-activities) – rafsanahmad007 Mar 17 '17 at 18:23