3

I have a frame layout which i use for swapping fragments. I use navigation drawer and every menu item opens a fragment. So it is sure that in the all app cycle there will be only 1 fragment on screen at the same time (and thus 1 activity). Below you can find my fragment start method

 public void startFragment(Fragment f)
{
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
    transaction.replace(R.id.fragment_container, f);
    transaction.commit();


}

So when i checked on Android Studio, everytime i replace fragment with above method, memory usage increases. FragmentTransaction.remove does not free fragments and replace also does not free too. So after a while if i click every menu item and open fragments over again and again, memory usage increases a lot.

So my question is how can i free old-replaced fragments? I want only one in memory. Or we can say; I want to destroy them

Mert Serimer
  • 1,217
  • 2
  • 16
  • 38
  • 1
    "The fact that fragment itself is destroyed and gc'ed does not mean all resources you allocated were removed too" ([1](http://stackoverflow.com/a/18352625/2668136)) - "This happens because Fragments that have a UI will hold references to UI components [views], and these Views hold a reference of the Activity's Context" ([2](http://stackoverflow.com/a/28834362/2668136)) - "[Activity: a new context and the old one intended to be garbage collected] It can't be garbage collected now since your Fragment still has a reference to the old one ." ([3](http://stackoverflow.com/a/13422819/2668136)) – Blo Jan 15 '16 at 21:58
  • @Fllo thanks for the explanation. So i will assign every context referenced variables to null ondestroyview in every fragment – Mert Serimer Jan 15 '16 at 23:55
  • @Fllo So i am assigning every ui elements to null and it seems it does not change much. What i changed is, Created a variable called mainView and assigned in onCreateView inflater.inflate. Then assign this variable null in onDestroyView It seems it makes a little difference. What am i doing wrong? – Mert Serimer Jan 16 '16 at 00:15

1 Answers1

1

Until your activity dies, all the references to its fragments will exist in memory. Regardless of add/remove operations that happened at Fragment Manager level / backstack.

Have a look on this stack overflow answer by Martín Marconcini.

A work around can be hiding and showing the frgaments if they exists in the back stack. Have a look on the this.

Community
  • 1
  • 1
Sanjeet A
  • 5,171
  • 3
  • 23
  • 40