Search code examples
androidoncreate

Why is it necessary to check savedInstanceState inside of OnCreate?


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();
    }
}

Solution

  • 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.