Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onAttach() or onActivityCreated(), which is the best place to read activity?

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

  • onAttach()
  • onActivityCreated

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

like image 752
Nandish A Avatar asked Feb 03 '14 09:02

Nandish A


People also ask

What are the differences between onCreate () onCreateView () and onActivityCreated () in fragments and what would they each be used for?

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.

Why onActivityCreated is now deprecated in fragment?

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.

Is onAttach called before onCreate?

In a Fragment's Lifecycle, the onAttach() method is called before the onCreate() method.

What does the onCreateView () method return if a fragment doesn't have any?

Returns The fragment's root view, or null if it has no layout.


1 Answers

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().

like image 97
Sergo Pasoevi Avatar answered Oct 13 '22 11:10

Sergo Pasoevi