Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you check for savedInstanceState == null when adding fragment?

Tags:

In the fragment doc, in one of the example, they check for savedInstanceState == null when adding a fragment:

public static class DetailsActivity extends Activity {      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);          if (getResources().getConfiguration().orientation                 == Configuration.ORIENTATION_LANDSCAPE) {             // If the screen is now in landscape mode, we can show the             // dialog in-line with the list so we don't need this activity.             finish();             return;         }          if (savedInstanceState == null) {             // During initial setup, plug in the details fragment.             DetailsFragment details = new DetailsFragment();             details.setArguments(getIntent().getExtras());             getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();         }     } } 

What is the purpose of this check? What would happen if it is not there?

like image 465
Chin Avatar asked Nov 11 '14 01:11

Chin


1 Answers

What is the purpose of this check?

To not add the fragment twice, though I prefer checking to see if the fragment is there instead of relying on that Bundle being null.

What would happen if it is not there?

Initially, nothing, as the Bundle will be null when the activity is first created.

However, then, the user rotates the device's screen from portrait to landscape. Or, the user changes languages. Or, the user puts the device into a manufacturer-supplied car dock. Or, the user does any other configuration change.

Your activity will be destroyed and recreated by default. Your fragments will also be destroyed and recreated by default (exception: those on which setRetainInstance(true) are called, which are detached from the old activity and attached to the new one).

So, the second time the activity is created -- the instance created as a result of the configuration change -- your fragment already exists, as it was either recreated or retained. You don't want a second instance of that fragment (usually), and therefore you take steps to detect that this has occurred and not run a fresh FragmentTransaction.

like image 113
CommonsWare Avatar answered Sep 21 '22 21:09

CommonsWare