I have fragments created that depends on few properties of its parent activity. I went through the Fragment Life cycle documents. I need to store the copy of activity in a variable so that I can access it later. There are two place, I could do this
Which is the best place that would be recommended and why? There has been instances that getActivity return null in the fragment after onAttach() is called
onCreate(Bundle) called to do initial creation of the fragment. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.
Need for onActivityCreated() deprecation In such similar fashion android developers saw the tight coupling of code dependent to the Activity's life cycle. And they decided that it is not a good practice anymore to be dependent on the activity attach to do certain things inside the fragment.
In a Fragment's Lifecycle, the onAttach() method is called before the onCreate() method.
Returns The fragment's root view, or null if it has no layout.
If getActivity() returned null after onAttach() was called, it would only have meant that the fragment was no longer attached to activity. So the safest place is still onAttach().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With