Failure saving state - target not in fragment manager (setTargetFragment)
android, android-fragments
Solution
There are actually two things you should do to resolve this issue:
1. Make sure you use getChildFragmentManager() NOT getFragmentManager() when launching FragmentB from FragmentA
Calling getChildFragmentManager() will return the hosting Fragment's FragmentManager, whereas getFragmentManager() will return the hosting Activity's FragmentManager. It's important to use getChildFragmentManager() because you're nesting a Fragment inside another Fragment, so the parent Fragment should be in charge of handling any transactions with the nested Fragment. If you use getFragmentManager(), you'll run into the issue you're experiencing right now.
2. DO NOT use setTargetFragment() and getTargetFragment(), they will not work when using getChildFragmentManager()
Instead, use getParentFragment(). I believe there is some kind of bug in Android right now where even if you properly call
`fragmentB.setTargetFragment(fragmentA, 0);`
and then show FragmentB, after a configuration change, calling getTargetFragment() from FragmentB will return itself instead of FragmentA.
Problem
I've got a monkey crash whereby ``` java.lang.IllegalStateException: Failure saving state: FragmentB has target not in fragment manager: FragmentA at android.support.v4.app.FragmentManagerImpl.saveAllState(FragmentManager.java:1561) at android.support.v4.app.FragmentActivity.onSaveInstanceState(FragmentActivity.java:475) at com.acme.ParentActivity.onSaveInstanceState(Unknown Source) ``` Basically FragmentA loads up FragmentB and `setTargetFragment` is called to set FragmentB's target fragment. FragmentB then simply calls `getTargetFragment`in its `onCreate` method and hangs on to the target for when needed. Now I'm not doing anything in any of the `onSaveInstanceState` calls with the target fragment in terms of setting it null, making any `saveFragmentInstanceState`, `putFragment` etc. calls. The question is should I be doing something with it? Thanks in advance, Peter. ** Edit 1 ** I am using an old version of the support library and have a feeling that this may be fixed in the latest version, will test further and provide a further update if that is the case. However, still interested to know whether I should be doing anything with the target fragment that I'm not currently doing. ** Edit 1 ** Fixed with version 8 of the support library (haven't tried others).