I really get confused with Fragment
lifecycle, especially for the time to call getActivity()
. Sometimes you cannot get Activity
by getActivity()
. And it always caused some puzzling bugs.
Thank you for anyone can solve the puzzle.
Bookmark this question. Show activity on this post. In a Fragment's Lifecycle, the onAttach() method is called before the onCreate() method.
onCreate is called on initial creation of the fragment. You do your non graphical initializations here. It finishes even before the layout is inflated and the fragment is visible. onCreateView is called to inflate the layout of the fragment i.e graphical initialization usually takes place here.
onStart() : is called after the onCreateView() method when the host activity is created.
getActivity() in a Fragment returns the Activity the Fragment is currently associated with. (see http://developer.android.com/reference/android/app/Fragment.html#getActivity()).
getActivity()
can be null while your fragment is in process of preparation and about to be ready.
The fragment life cycle is bound to callback methods. These method will be called somewhere in time while fragment is preparing.
getActivity()
will be a valid instance. It happens after onCreateView()
thoughYour safest bet for activity existence is:
According to the current documentation (Dec 2018), it shows that onAttach()
is called right at the beginning before onCreate()
and onCreateView()
. It should be safe to getActivity()
in these methods.
In the Support v4 Fragment documentation for onActivityCreated()
it says that this method is:
Called when the fragment's activity has been created and this fragment's view hierarchy instantiated.
The important part here is that the "activity has been created" i.e. Activity.onCreate()
has finished executing. Before this point we are still within that method.
This can be confirmed by looking at the FragmentActivity.onCreate()
source code you can follow the process of fragments being attached to the activity at the start of the method, then the fragment state being restored etc etc. So the activity should be valid in all those places, but technically it has not finished with the whole create process.
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