I have fragments I keep in the backstack of FragmentManager. Every fragment state is saved for orientation changes with member variables, like this for example:
@Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putLong("userId", mUserId); outState.putString("username", mUsername); }
My problem is that if there is an orientation change, since every fragment in the backstack gets called via onSaveInstanceState, I get a null pointer exception because the member variables don't exist anymore.
Any ideas on how to solve this?
Note that onSaveInstanceState() is called when your activity goes into the background and NOT when the app process is about to be killed.
add() - (create and) add a Fragment B and it overlap Fragment A, which is still active in the background. remove() - can be used to remove Fragment B and return to A. Fragment B will be recreated when called later on.
Here is an example: @Override protected void onCreate(Bundle savedInstanceState) { super. onCreate(savedInstanceState); if (savedInstanceState == null) { myFragment = MyFragment. newInstance(); getSupportFragmentManager() .
The onSaveInstanceState() method allows you to add key/value pairs to the outState of the app. Then the onRestoreInstanceState() method will allow you to retrieve the value and set it back to the variable from which it was originally collected.
It is possible that your member variables don't exist anymore because the FragmentManager
in your Activity
is dying with all of your fragments.
You need to override the method onSaveInstanceState
of your Activity
class as well, because you need to save the Activity
state before you save the Fragments
state.
As the documentation says:
There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.
UPDATE
In your Activity
onSaveInstanceState
and onRestoreInstanceState
, try saving you Fragment
references and then restore them with something like this:
public void onSaveInstanceState(Bundle outState){ getFragmentManager().putFragment(outState, "myfragment", myfragment); } public void onRestoreInstanceState(Bundle inState){ myFragment = getFragmentManager().getFragment(inState, "myfragment"); }
Tell me then if you had luck! :-)
Building on Jorge Gil - 'xɔɾ.xɛ xil answer Note the following:
Sorry for being Captain obvious!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With