popBackStack() after addToBackStack does not work

You should call

fragmentTransaction.addToBackStack(null);

after performing all operations such as add(), remove(), and replace() and Just before commit(). Only then this transaction will be added to backstack. Only then you will be able to return to previous fragment state with Back button. Details here.


I will suggest using the fragment replacement with Tag to produce the same result .

Add the fragment B to activity with tag

fragmentTransaction.replace(R.id.main_fragment_container, new FragmentB(),"TAG_B");

Fragment A -> Fragment B [onBackPressed] -->Fragment A Override the onBackPressed() in the Activity files where ,

// check for fragment B and you are viewing fragment B

if (getSupportFragmentManager().findFragmentByTag("TAG_B")!=null)  
{
    fragmentTransaction.replace(R.id.main_fragment_container, new FragmentA(),"TAG_A");
}

addToBackStack("TAG") and popBackStackImmediate("TAG") always revert to fragment condition without any data in the UI right before fragment is created or added to activity !


The problem is you're mixing Fragment and methods from the support library.

If you are using the support library, make sure:

  • your Activity extends from the android.support.v4.app.FragmentActivity
  • your Fragment extends from android.support.v4.app.Fragment
  • use getSupportFragmentManager() to get the android.support.v4.app.FragmentManager

Your 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:

  • your Activity extends from the android.app.Activity
  • your Fragment extends from android.app.Fragment
  • use getFragmentManager() to get the android.app.FragmentManager

Your 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.


You use the getSupportedFragmentManager() to replace FragmentA by FragmentB. But you call popBackStack() on the getFragmentManager().

If you are adding the Fragments to the android.support.v4.app.FragmentManager you also have to call popBackStack() on the same FragmentManager.

This code should solve the problem:

if (getSupportFragmentManager().getBackStackEntryCount() > 0){
    boolean done = getSupportFragmentManager().popBackStackImmediate();
}