9

I am using this code to clear up my backstack up to my main view:

while(mFragmentManager.getBackStackEntryCount() > 1) {
            mFragmentManager.popBackStack(null, 0);
}

I am pretty sure this code was working before, but now the backstack count does not change and no Fragment is being removed, which causes an out of memory exception because the while loop keeps running.

Does anyone know, if there is something wrong with it, or if there is a bug in the latest revision of the SDK-tools. I have no clue what's causing the problem.

Nickolaus
  • 4,785
  • 4
  • 38
  • 60
  • look at this [question](http://stackoverflow.com/questions/13086840/actionbar-up-navigation-with-fragments) ; – SohailAziz Jan 22 '13 at 10:48
  • the code is inside my onOptionsItemSelected method, and as I said it was working before. I didn't use the function for about 3 weeks or so and now it didn't seem to work anymore – Nickolaus Jan 22 '13 at 10:59
  • additionally if you are refering to .popBackStack() without arguments, this has the same effects and doesn't work either – Nickolaus Jan 22 '13 at 11:09
  • 1
    However, you may try `mFragmentManager.popBackStackImmediate(null, 0);` although you're probably better off calling `mFragmentManager.popBackStackImmediate(mainTag, mFragmentManager.POP_BACK_STACK_INCLUSIVE)` and ditch the loop – Matt Jan 24 '13 at 18:13

4 Answers4

11

You are probably looking for popBackStackImmediate(). This immediately executes a back stack pop.

christiandeange
  • 1,175
  • 12
  • 17
7

you can also use .executePendingTransactions(); after popBackStack();

elp
  • 8,021
  • 7
  • 61
  • 120
Alexander Thiele
  • 657
  • 5
  • 13
6

I certainly would not assume that popBackStack() has an immediate effect, which your loop appears to do.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
3

What documentation says for popBackStack():

Pop all back stack states up to the one with the given identifier. This function is asynchronous -- it enqueues the request to pop, but the action will not be performed until the application returns to its event loop.

So after mFragmentManager.popBackStack(null, 0); your backstack is not empty until your event is completely processed.

Use popBackStackImmediate() for empty it immediately in the current event itself.

Nickolaus
  • 4,785
  • 4
  • 38
  • 60
Mufazzal
  • 873
  • 6
  • 12