Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment creation in onCreate?

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?)

like image 775
Joakim Engstrom Avatar asked Aug 01 '13 09:08

Joakim Engstrom


1 Answers

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).

like image 199
user Avatar answered Oct 28 '22 14:10

user