Rahul
Rahul

Reputation: 372

Android : How to remove fragments from fragment manager

I am developing Android App. In a single activity I am replacing fragments. After some iterations my app gets closed without any force close message and no exception.

While searching I got one thing. If I track number of fragments on fragment manager using

getSupportFragmentManager().getFragments().size() 

it keeps on incrementing while there is only one fragment which is active and no fragment present in back stack as I am replacing fragments.

Example :

Here is code which I am using for fragment transaction:

getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.content, fragmentStep1,
                    ApplicationTags.FRAGMENT_TAG_PAGE_1)
            .disallowAddToBackStack().commit();
    getFragmentManager().executePendingTransactions();

I need to remove all these fragments from fragentmanager for reducing memory usage by app.

Please help me with this one. Thanks in advance.

Upvotes: 1

Views: 3653

Answers (5)

outta comfort
outta comfort

Reputation: 406

I guess, if you run through your ArrayList of fragments returned by getFragments() you will see, that all of them are null except the one which is in fact active. So it is not the issue.

(That is what happened the time I tried to figure out why there seemed to be more active fragments in my activity than I had expected)

Upvotes: 0

heloisasim
heloisasim

Reputation: 5016

You could remove all fragments when they reach a certain number.

// set your own max stack size
MAX_STACK_SIZE = 20;

int stackSize = getBackStackEntryCount;
if(stackSize>20)
FragmentManager fm = getSupportFragmentManager();
for(int i = 0; i < stackSize; ++i) {
    fm.popBackStackImmediate();
}

Upvotes: 0

SohailAziz
SohailAziz

Reputation: 8034

You can get the number of fragments on BackStack by getFragmentManager().getBackStackEntryCount();

as you are replacing fragments and not saving the previous fragment on BackStack, there will be exactly one fragment at a time. So the issue is not with fragments.

Upvotes: 0

BladeCoder
BladeCoder

Reputation: 12949

If it was a memory issue you would get an OOM error in your Log. The code you posted is correct. The issue must be something else.

Upvotes: 0

Tronum
Tronum

Reputation: 717

Try to getFragmentManager().popBackStack(); after .commit()

Upvotes: 1

Related Questions