In addition to the aforementioned comments, I believe it is important to note that if you are attempting to use the onAttach()
to update data contained inside the fragment from the parent Activity, it is possible to run into issues when the collection variable inside the Activity is null or empty when the fragment is inflated. At some point inside your Activity's life cycle, your data model may change and need to be updated inside the fragment. You might attempt to get a reference to a fragment already inflated, but find as you step through your code that onAttach()
never fires, even when using the override containing a Context or Activity object.
If you are attempting to create a listener for the fragment and initialize the listener from the onAttach()
callback method, onAttach()
will not fire unless you provide the tag parameter as shown below when adding the fragment to the Activity:
// in the Activity
getFragmentManager().beginTransaction()
.add(
R.id.fragmentContainer,
CustomFragment.newInstance(customDataSource),
CustomFragment.TAG // Must be passed in for the code below to work
).commit();
// Getting a reference to the fragment later on (say to update your data model inside the fragment (in onActivityResult())
CustomFragment fragmentDelegate = (CustomFragment) getFragmentManager().findFragmentByTag(CustomFragment.TAG);
fragmentListener.updateDataSource(customDataSource);