1

What is the purpose of the if block in the onCreate() method? Why is it necessary to check if savedInstanceState is null?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }
}
AdamMc331
  • 16,492
  • 10
  • 71
  • 133
  • Apologies. I am a newbie here :/ –  Jul 07 '15 at 20:03
  • @njzk2 depending on how new someone is, they may not know where to find the documentation. In this case, Abhijit, you can use [this link](http://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle)) for more info. To quote the docs regarding the parameter: "If the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in onSaveInstanceState(Bundle). Note: Otherwise it is null." – AdamMc331 Jul 07 '15 at 20:10
  • @McAdam331 This is android, the documentation is in the IDE. It is in google. It is right next to where you download the SDK. It is in stackoverflow. It is everywhere! (Don't take my word for it. Just Google `onCreate`.) – njzk2 Jul 07 '15 at 20:54

2 Answers2

4

When your activity is recreated, such as after a screen rotation or other configuration change, fragments are automatically reattached. By checking if savedInstanceState == null, you ensure that you are not re-adding a fragment that has already been added for you.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
0

Well that's so you can remember where someone was when they last left your app. So for instance chrome remembers your last visited tabs.

trinityalps
  • 397
  • 4
  • 19