My project contains two fragment :
fragmentA when a c
The problem is you're mixing Fragment and methods from the support library.
If you are using the support library, make sure:
Activity extends from the android.support.v4.app.FragmentActivityFragment extends from android.support.v4.app.FragmentgetSupportFragmentManager() to get the android.support.v4.app.FragmentManagerYour code in the Activity would be:
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStackImmediate();
}
Please be aware that if you would like to get the FragmentManager from the Fragment code, you have to use the getFragmentManager method, as explained in the documentation (probably that's the cause of some confusion if you don't have much experience).
If you are not using the support library:
Activity extends from the android.app.ActivityFragment extends from android.app.FragmentgetFragmentManager() to get the android.app.FragmentManagerYour code would be:
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStackImmediate();
}
fragmentTransaction.commit(); is not necessary in both cases, so remove it.
Also, please call fragmentTransaction.addToBackStack(null); just before the commit but after the other operations.