Looking at the Fragment lifecycle (e.g. here), the Activity seems to be attached to the Fragment before any other callback is issued (this is notified by the onAttach()
method).
In my application, which consist of a single activity, the first Fragment is opened from the onCreate()
method of the Activity (actually it is the last thing done inside onCreate()
).
Currently, I'm initializing all my graphical elements inside the onCreateView()
callback, including the instantiation of some object (like an ArrayAdapter
) which require the Activity to be constructed, which is obtained calling getActivity()
. I assume that the Activity is guaranteed to exist at this point, since the onAttach()
method has already been called.
I noticed that IntelliJ warned me about the possibility of getActivity()
returning null
, maybe just because the method is annotated as @Nullable
, so I started to search on the web if my assumption was actually true, and now I'm confused: is it actually safe to call getActivity()
inside onCreateView()
? Why is there a method called onActivityCreated()
(I know it is now deprecated, but it surely served a purpose when it wasn't)?
Unfortunately the documentation does not help to understand this.