getBackStackEntryCount() always returns 0 even after adding addToBackStack and executePendingTransactions()

user3555350 picture user3555350 · Mar 19, 2015 · Viewed 16.8k times · Source

I have two activities A and B. Activity A has a mapFragment and I am adding it to backstack. When I come back from to Actvity A from B, I want the fragment to show up in same state as I left it. But getFragmentManager().getBackStackEntryCount() is returning me 0. Here is my code:

MapFragment mMapFragment = MapFragment.newInstance();
    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
    mMapFragment.getMapAsync(this);
    fragmentTransaction.replace(R.id.container, mMapFragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
    getFragmentManager().executePendingTransactions();

When coming back from activity B, I have this to know number of getBackStackEntryCount():

System.out.println("Number of entries in backstack "+ getFragmentManager().getBackStackEntryCount());

which is showing me 0.

Thanks in advance.

Answer

Neonigma picture Neonigma · Aug 17, 2015

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();         
    }
}