I had a similar problem, in my case getFragmentManager().getBackStackEntryCount() was always returning zero.
My problem was I've using support fragments:
Fragment fragment = new MyFragment();
// note getSupportFragmentManager() instead getFragmentManager()
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame, fragment)
.addToBackStack(null)
.commit();
fragmentManager.executePendingTransactions();
and I've checking getFragmentManager() backStackEntryCount, which always returns zero (it's using another fragment manager):
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0 ) {
getFragmentManager().popBackStack();
}
}
instead of getSupportFragmentManager, which returns the correct number:
@Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0 ) {
getSupportFragmentManager().popBackStack();
}
}
Hope it helps!