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