getBackStackEntryCount() always returns 0 even after adding addToBackStack and executePendingTransactions()
Solution 1:
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();
}
}
Solution 2:
Try this:
MapFragment mMapFragment = MapFragment.newInstance();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
mMapFragment.getMapAsync(this);
fragmentTransaction.add(R.id.container, mMapFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
getFragmentManager().executePendingTransactions();
I have changed this line:
fragmentTransaction.replace(R.id.container, mMapFragment);
to this:
fragmentTransaction.add(R.id.container, mMapFragment);
Pretty sure if you replace a fragment then its not in the backstack :)
Solution 3:
I has similar problem. Thanks to this answer i create below code in my activity, instead of fragment, and this solution work fine:
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Log.d("ovech", "back stack changed");
Log.d("ovech", "back stack count = " + getSupportFragmentManager().getBackStackEntryCount());
if(getSupportFragmentManager().getBackStackEntryCount()>0) {
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
} else {
toolbar.setNavigationIcon(null);
Log.d("ovech", "hello without icon");
}
toolbar.invalidate();
}
});