6

I'm reading Programming for Android and in the book it says:

It is entirely possible that an activitys onCreate will be called while it is still associated with a previously created fragment. Simply adding a new fragment whenever onCreate method is called will leak fragments. To prevent that, the example code makes use of the fragment managers tagging and location features.

The code is:

super.onCreate( state); 
setContentView( R.layout.main); 
FragmentManager fragMgr = getFragmentManager(); 
FragmentTransaction xact = fragMgr.beginTransaction(); 
if (null = = fragMgr.findFragmentByTag( FRAG1_TAG)) { 
   xact.add( R.id.date_time, new DateTime(), FRAG1_TAG); 
} 
xact.commit();

Can someone explain why this is needed in onCreate?

I thought that a fragments lifecycle was always dependent on the activity's lifecycle, and onCreate in an activity is always called when the activity is created (i.e it is always dead).

So if a fragments lifecycle is tied to the activity, shouldn't all the fragment die when an activity dies and therefore the fragments will always be null when onCreate is called in an Activity?

Are there exceptions or can someone explain why my thinking is not correct (I actually think it is not correct but have no idea why?)

Joakim Engstrom
  • 6,243
  • 12
  • 48
  • 67
  • 1
    The fragments will get destroyed with the `Activity` but the `FragmentManager` will remember them(unless you're completely finishing the activity). Now, if the activity gets recreated(after a configuration change for example) the `FragmentManager` needs to restore any previously committed fragments and that is why you check to see if the fragment isn't already in the `FragmentManager`. If it's there then abort the transaction otherwise will end up with two fragments(the new one that you just instantiated and the old one that the `FragmentManager` remembered). – user Aug 01 '13 at 09:22
  • Okay, that is exactly what I wanted. So the lifecycle is tied to the activity I guess but the FragmentManager still remembers the instance of the Fragment. Makes sense. – Joakim Engstrom Aug 01 '13 at 09:28
  • Can you post it as an answer so I can mark it as accepted? – Joakim Engstrom Aug 01 '13 at 09:28

1 Answers1

3

The fragments will get destroyed with the Activity but the FragmentManager will remember them unless you're completely finishing the Activity. If the Activity is killed due to a configuration change and then it gets recreated the FragmentManager needs to restore any previously committed fragments. That is why you check to see if the Fragment isn't already in the FragmentManager. If it's there then abort the transaction otherwise will end up with two fragments(the new one that you just created and the old one that the FragmentManager remembered and it will restore).

user
  • 86,916
  • 18
  • 197
  • 190