Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 833
KairisCharm Avatar asked Jun 26 '13 20:06

KairisCharm


2 Answers

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();
    }
  }
like image 179
CommonsWare Avatar answered Sep 27 '22 21:09

CommonsWare


Ok, your solution worked, except instead of using:

 if (getSupportFragmentManager().findFragmentById(android.R.id.content)==null)

I used:

 if (savedInstanceState==null)

Apparently the fragment manager is not set up by the onCreate function. But, since your answer is mostly correct, I'm marking it as an answer.

I want to thank you again. This is the second time you've been a big help to me, and I really appreciate it.

like image 32
KairisCharm Avatar answered Sep 27 '22 21:09

KairisCharm