Search code examples
androidcrashfragmenttransaction

Android: When is it appropriate to use FragmentTransaction.remove?


I thought I had understood that you're supposed to call FragmentTransaction.add() in onCreate() and FragmentTransaction.remove() in onDestroy(). My app crashes in onDestroy() with this error:

06-26 15:25:50.213: E/AndroidRuntime(579): java.lang.RuntimeException: Unable to destroy activity {com.myapp/com.myapp.MainActivity}: java.lang.IllegalStateException: Activity has been destroyed

When do I call these things if not in onCreate/onDestroy()?


Solution

  • My problem with that is that when I switch to my horizontal view, and then back to my vertical view, I now have a duplicate layout for at least one of the nested fragments.

    My guess is that this is because you are always adding the fragment in onCreate(). Android automatically recreates fragments on configuration changes. Hence, onCreate() should check to see if the fragment already exists before adding it:

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        if (getSupportFragmentManager().findFragmentById(android.R.id.content)==null) {
          getSupportFragmentManager().beginTransaction()
                                     .add(android.R.id.content,
                                          new RotationFragment()).commit();
        }
      }