I made a very simple Activity which shows a simple ListFragment like below:
My Activity:
public class MyActivity ex
super.onCreate(savedInstanceState) will call onCreate method in FragmentActivity, which will call mFragments.attachHost(null /*parent*/);
This sentence will assign a value to mHost
in FragmentController, when you calls FragmentTransaction.commit() ,
In the method enqueueAction()
,it has this sentences
if (mDestroyed || mHost == null) {
throw new IllegalStateException("Activity has been destroyed");
}
So if you haven't call super.onCreate(savedInstanceState) before you commit a fragmentTransaction, you will get this exception because mHost is null
Still bad, because got error “Activity has been destroyed”
ava.lang.IllegalStateException: Activity has been destroyed fragmentTransaction.commitAllowingStateLoss();
So my solution is add check if (!isFinishing()&&!isDestroyed())
if (!isFinishing()&&!isDestroyed()) {
fragmentTransaction.commitAllowingStateLoss();
}
}
Just to make sure I'm seeing this right, MyActivity is the activity that you're trying to launch and then add an instance of FirstFragment into, right?
Immediately I see two things that you need to look at
1) In your activity you never call setContentView() or super.onCreate(). The first call could be a huge issue for you because that means that your layout was never inflated, and therefore, the R variable doesn't exist
2) Your MyActivity needs to have its own xml layout file, which it doesn't have.
If any one come across similar type of issue:
I was facing same time of issue, but in my case from Main Activity I was calling to Fragment1 and then if user click on Fragment1 Layout I want to launch another Fragment2 Layout.
I was able to launch Fragment1 from Main activity but Fragment1 to Fragment2 it was failing with exception as "Activity has been destroyed" .
I resolved above issue by maintaining FragmentManager object as static in MainActivity class. private static FragmentManager mfragmentManager = null;
calling to both fragment using same above object, resolved my issue.
Below is my Fragment switching code from Main Activity.
public void switchToFragment(String fragmentName){
Fragment fragment = null;
switch (fragmentName) {
case "Fragment1":{
fragment = new Fragment1();
break;
}
case "Fragment2": {
fragment = new Fragment2();
break;
}
}
FragmentTransaction transaction = mfragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
I figured out myself, It is because I missed the super.onCreate(savedInstanceState);
in my Activity onCreate() method . After added this, things are fine.
I faced the same issue and unable to fix it. Event I added isFinishing() check as well. but no luck.
then I added one more check isDestroyed() and its working fine now.
if (!isFinishing() && !isDestroyed()) {
FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction();
ft.replace(LAYOUT_ID, myFragmentInstance);
ft.commit();
}