committedandroider committedandroider - 1 year ago 63
Android Question

Are fragments saved by default with savedInstanceState?

I read on What's onCreate(Bundle savedInstanceState)
that onsaveinstancestate gives you a bundle of the previous state of the application(if the orientation of the screen changed.

I looked on the Android docs( and saw that you have to manually put the values you want saved as key value pairs. Their code for doing so was

static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";

public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

My question is for fragments, are they automatically reattached when the orientation changes and the activity recreated? Would you have to put code to save it into a bundle?
Heres facebook code for this situation that I am trying to understand

public void onCreate(Bundle savedInstanceState) {

if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
.add(, mainFragment)
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()


Answer Source

To keep a fragment when an Activity gets destroyed, so it automatically reataches, you should call


in the Fragment's constructor. Nothing is saved by default in onSaveInstanceState()