Android Fragments recreated on orientation change

Luke47 picture Luke47 · May 17, 2012 · Viewed 22.1k times · Source

I'm developing an app that basically has an ActionBar. When my app starts, the Activity creates the fragments and attaches them to each tab, so when I switch I get different views.

The problems arise when I try to rotate the device. After some struggle, I noticed that Android automatically recreates the previously added fragments like this:

SummaryFragment.onCreate(Bundle) line: 79   
FragmentManagerImpl.moveToState(Fragment, int, int, int) line: 795  
FragmentManagerImpl.moveToState(int, int, int, boolean) line: 1032  
FragmentManagerImpl.moveToState(int, boolean) line: 1014    
FragmentManagerImpl.dispatchCreate() line: 1761 
DashboardActivity(Activity).onCreate(Bundle) line: 864  
...

and then I recreate the fragments as usual. So I have the "real" fragments that I expect to work correctly and their "hidden" Android-created counterparts that make my app crash. How can I avoid this behavior? I already tried to call setRetainInstance(false) in the SummaryFragment.

Thank you

Answer

Barak picture Barak · May 17, 2012

You need to check for a savedInstanceState [edit: in your parent activity], and if it exists, don't create your fragments.

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

    if (savedInstanceState == null) {
         // Do your oncreate stuff because there is no bundle   
    }
// Do stuff that needs to be done even if there is a saved instance, or do nothing
}