Today's #AndroidDev #Protip by +Bruno Oliveira is about creating and adding your Fragments correctly.

Configuration changes are a part of life. When they happen, your Activity might be destroyed and re-created. Setting a fixed orientation for your Activity in your app's manifest (or adding "orientation" to your configChanges) doesn't mean you are safe from this: many other configuration changes are possible.

Now, when your Activity is destroyed and re-created as a result of a configuration change, your Fragments will also be destroyed and re-created. Then all you have to do is add them again, and you're all set, right?

Wait! If you are creating Fragments at run-time (as opposed to statically defining them in a layout file), here is where you have to be careful: when your Activity is being created for the first time, you should add your Fragments in onCreate(). However, when your Activity is being re-created, the framework will add your Fragments back to the Activity as they were before it was destroyed, so it's an error to add them again.

How can you detect whether or not you should add a Fragment in onCreate()? Easy: just check the savedInstanceState argument. If it's null, you should add the fragment. If not, don't add the fragment (it's already there). Example:

public class MyActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        // Only add fragment if this is the initial Activity creation
        if (savedInstanceState == null) {
            FragmentManager fragmentManager = 
            FragmentTransaction fragmentTransaction = 
            ExampleFragment fragment = new ExampleFragment();
            fragmentTransaction.add(, fragment);
        } else {
            // Don't add the fragment!
            // (and use savedInstanceState to restore Activity state)

If you fail to include this check, you might end up in a very strange state where you have overlapping Fragments in the same container. 

That's all for today's protip! For more information on Fragments, see the Fragments API Guide at and our training lesson at
Fragments | Android Developers
Fragments | Android Developers
Shared publiclyView activity