24

the docs on setRetainInstance say :

This can only be used with fragments not in the back stack.

so I started playing with it.

I have one Activity with adds first frag A

FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content, new PackageFragment());
ft.commit

then from this frag I run a method from parent Activity which adds frag B to backstack

FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content, new OrderFragment());
ft.addToBackStack(null);
ft.commit();

then I create log msg from onCreate,onDestroy,onSaveInstanceState,onActivityCreated...etc

I try two versions of this process. Rotating the device on each fragment.

  1. default

Everything is as expected. onCreate, onDestroy on fragments fire

  1. setRetainInstance(true)

Everything is as expected?. onCreate, onDestroy on fragments dont fire

and all seems to work while fragments are in the backstack.. so why the docs say I shouldnt use it? What are the scenarios where I might get in trouble?

thanks

AndroidGecko
  • 14,034
  • 3
  • 35
  • 49
  • When you press the back button is when you start seeing the difference. So for example if you used setRetainInstance on a detail view fragment that temporarily shows up, pressing back might take you out of the app instead of closing this temporary detail view fragment. – Marco RS Nov 16 '12 at 19:09
  • Thanks Marco, were you able to reproduce this problem? please share if so. I can press back with no problem. I tested several scenarios and always the detail fragment is destroyed properly when I press back while both frags have setRetainInstance(true). – AndroidGecko Nov 19 '12 at 12:07
  • I take back my comment. I am seeing a similar behavior.... – Marco RS Dec 07 '12 at 04:21

1 Answers1

26

Updated answer:

What are the scenarios where I might get in trouble?

When adding a Fragment to the back stack and passing a Bundle in the Fragment from onSaveInstanceState() to onCreateView() on configuration change. Calling setRetainInstance(true) will set the Bundle to null on configuration change.

(I'm not sure a developer would actually attempt this since using setRetainInstance(true) makes onSaveInstanceState() kind of redundant, but I didn't see the behaviour documented in the API docs so I wrote up this answer).

If both addToBackStack() and setRetainInstance(true) are called, setRetainInstance() partly alters the Fragment lifecycle method calls and parameter values on configuration changes, compared to calling only addToBackStack().

Specifically, in the test below, looking a differences between calling only addToBackStack() and calling setRetainInstance(true) as well, and seeing what happens on configuration change:

Calling addToBackStack() but not setRetainInstance(true);

  • onCreate() and onDestroy() are called.
  • a bundle passed from onSaveInstanceState() is received as a parameter in onCreateView().

Calling both addToBackStack() and setRetainInstance(true):

  • onCreate() and onDestroy() are not called. This is metioned in the API docs.
  • a bundle passed from onSaveInstanceState() is not received in onCreateView(). The passed-in Bundle is null.

A test with logged method calls and parameters tested for null:

In the Activity:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MyFragment fragment;
    if (savedInstanceState != null) {
        fragment = (MyFragment) getFragmentManager().findFragmentByTag("my_fragment_tag");
    } else {
        fragment = new MyFragment();
        FragmentTransaction t = getFragmentManager().beginTransaction();
        t.addToBackStack(null);//toggle this
        t.add(android.R.id.content, fragment, "my_fragment_tag").commit(); 
    }
}

In the Fragment:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);//toggle this
}

and

@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putString("test", "value");
    super.onSaveInstanceState(outState);
}

Test 1: Fragment lifecycle when addToBackStack() is called , and setRetainInstance(true) is not called

  • onAttach()
  • onCreate()
  • onCreateView()
  • onActivityCreated()
  • onStart()
  • onResume()

[Device rotated from portrait to landscape]

  • onPause()
  • onSaveInstanceState()
  • onStop()
  • onDestroyView()
  • onDestroy()
  • onDetach()
  • onAttach()
  • onCreate()
  • onCreateView() with bundle param != null
  • onStart()
  • onResume()

Test 2 & 3: Fragment lifecycle calls with setRetainInstance(true) called, addToBackStack() called / not called (same result):

  • onAttach()
  • onCreateView()
  • onActivityCreated()
  • onStart()
  • onResume()

[Device rotated from portrait to landscape]

  • onPause()
  • onSaveInstanceState()
  • onStop()
  • onDestroyView()
  • onDetach()
  • onAttach()
  • onCreateView() with bundle param == null
  • onStart()
  • onResume()
Gunnar Karlsson
  • 28,350
  • 10
  • 68
  • 71
  • 1
    "whereas adding a Fragment to the backstack results in this lifecycle" -- do you have a reference for this? Looking at the code, I do not see where the call to `onAttach()` is dependent upon whether or not the fragment is to be added to the back stack. Thanks! – CommonsWare Dec 08 '12 at 02:04
  • Thanks for pointing this out. I meant when navigating backwards, not when just adding a Fragment. I've edited the sentence to express more clearly what I meant. This is a reference I used: http://assets.en.oreilly.com/1/event/68/Fragments%20for%20All%20Presentation.pdf. Section 19: "If you call addToBackStack() when removing or replacing a fragment:(...)If the user navigates back, the system invokes onCreateView(), onActivityCreated(), onStart(), and onResume() on the fragment." – Gunnar Karlsson Dec 08 '12 at 10:36
  • Another reference is Professional Android 4 Application Development by Reto Meier, Figure 4.9 (summary of Fragment lifecycle) "Fragment.onCreateView()(...)Fragment returns to the layout from the backstack". – Gunnar Karlsson Dec 09 '12 at 07:32
  • 1
    The API docs you are quoting are specifically for when the activity is being recreated after a configuration change. More concretely, if the activity has not been recreated, onAttach() is not called when navigating back to a removed fragment stored on the back stack, even if setRetainInstance(true) has been called. When an activity is being recreated with a fragment on the back stack, non-retained fragments will receive onAttach() immediately, whilst retained fragments will receive onAttach() only when they are navigated to again. – antonyt Dec 09 '12 at 12:34
  • @antonyt Thanks for your insightful comment. I've posted an updated answer. – Gunnar Karlsson Dec 10 '12 at 05:17
  • 1
    @GunnarKarlsson I see `savedInstanceState != null` even `setRetainedInstance(true)` in `onCreateView()`. May be this behaviour has changed since you last posted. Can anyone confirm? – Saqib Apr 04 '15 at 02:16