Search code examples
androidandroid-fragmentsmemoryfragmentmanager

Remove OLDEST commited back stack Fragments


I have a navigation drawer menu (with just a few items) that invokes switching fragments, something like this:

 FragmentTransaction trans = fragmentManager
            .beginTransaction()
            .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
            .replace(R.id.container, newFragment)
            .addToBackStack(String.valueOf(item.Index)); // item.Index is clicked nav. drawer item index

    trans.commit();

Now, when the user navigates in the application using the drawer, the back stack keeps growing and growing. When there are many items in the stack (say > 30 or something like this), some amount of memory is being used, which I don't like, because there's a danger that at some point it'll reach the critical point and I'll get OOMException.

So is there any way to remove the OLDEST items from the back stack? I don't want to use popBackStack() (and similar) because it will delete the NEWEST item and I want to get rid of the first (oldest) items since the user won't probably remember where he/she was 10 navigations earlier.


Solution

  • I've found some sort of a workaround so I'll answer my own question, maybe someone will find it useful.

    Since there's no way of removing the oldest stack from FragmentManager, I've decided to thrown it away and go with my own 'back stack' implementation.

    More details here: http://stuffleftatparty.com/android-app-will-eat-its-entire-memory-by-design