what is the different between onCreate() and onCreateView() lifecycle methods in Fragment? - android

I don't know when to use onCreate() or onCreateView().
I have used onCreate() and onCreateView() lifecycle methods.
I think onCreate() for Activity and onCreateView() for Fragment. But I am not sure. Can I use onCreate() LifeCycle method in Fragment? I hope somebody can help me!

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. It is always called some time after the onCreate method.

Activity lifecycle explained - http://developer.android.com/reference/android/app/Activity.html
Fragment lifecycle explained - http://developer.android.com/guide/components/fragments.html#Creating
Detailed lifecycle diagram - https://github.com/xxv/android-lifecycle

From documents :
onCreate
Called when the activity is starting.
This is where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById(int) to programmatically interact with widgets in the UI, calling managedQuery(android.net.Uri, String[], String, String[], String) to retrieve cursors for data being displayed, etc.
You can call finish() from within this function, in which case onDestroy() will be immediately called without any of the rest of the activity lifecycle (onStart(), onResume(), onPause(), etc) executing.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
Link to documentation of onCreate
onCreateView
Called to have the fragment instantiate its user interface view. This is optional, and non-graphical fragments can return null (which is the default implementation). This will be called between onCreate(Bundle) and onActivityCreated(Bundle).
If you return a View from here, you will later be called in onDestroyView() when the view is being released.
Link to documentation of onCreateView

Related

Is there any misunderstanding about the onActivityCreated fragment callback?

onActivityCreated seems to mean "This fragment callback is executed just after the activity has been... created... I mean, just after the fragment is correctly attached to the activity. There, you can safely call getActivity, it won't return null, except if the activity is null for some special reason".
However, I've seen that the fragment callback onAttach is called even after OnCreate, it means that the fragment has been attached to the activity, which has been created.
The complete workflow for a fragment (and for a fragment dialog, which is frequently left behind) is: onAttach -> onCreate -> onCreateView -> onActivityCreated. So in each of these 4 methods (perhaps not onAttach I don't know), the activity is normally not null and attached to the fragment.
So my question is: why does the callback onActivityCreated since the activity is, in fact, already created and attached to the fragment 3 callbacks ago???
So basically in onAttach() we get confirmation is that activity is attached to my fragment, I can use getActivity() to fetch things like resources like
getActivity().getResources.getDrawable(R.drawable.abc)
but Suppose if You want to fetch the views inflated in activity's xml like If you want to access
getActivity().findViewById(R.id.Myelement)
You might get null here, so OnActivtyCreated() ensures that activity's view is inflated, You can access activity's views now (Activity's view has been created (onActivityCreated))

Reusing Activity and Fragment objects

Is it possible that an Activity or Fragment object can be reused by Android system after onDestroy() is called?
In other words: is every call for onCreate() for Activity object and respectively onAttach() for Fragment object preceded by calling its constructor?
You shouldn't do that. Only framework should call methods like onCreate, onAttach etc..
After onDestroy activity should not be used!
ActvitiyLifecycle
Fragments

When to use onActivitycreate() and onCreate() in fragments [duplicate]

This question already has answers here:
Android: Where to put activity's onCreate() code in a fragment?
(2 answers)
Closed 8 years ago.
I have started working on fragments.Before starting i wanna clear a doubt whether when to use
onActivitycreate() and onCreate().I did many research but cound not find any relevent answer.Please help.
onActivitycreate() :
onActivitycreate() Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. It can be used to do final initialization once these pieces are in place, such as retrieving views or restoring state. It is also useful for fragments that use setRetainInstance(boolean) to retain their instance, as this callback tells the fragment when it is fully associated with the new activity instance. This is called after onCreateView(LayoutInflater, ViewGroup, Bundle) and before onViewStateRestored(Bundle).
onCreate():
The system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
Read this doc for more details: Fragment Activity Life cycle
onCreate() is sort of like a constructor for the Fragment class, where you normally initialize some variables. In many cases onCreate() is not overriden at all, although it is important to manually define a public empty constructor for every Fragment class.
onCreateView() is the most important method to override when you a create a Fragment (at any rate a Fragment that has a UI). It is analogous to the onCreate() of an Activity: here you inflate the View of the Fragment.
onActivityCreated() is called after the Activity to which the Fragment is attached has been created (i.e. the Activity's onCreate() method has returned without errors) and after the Fragment's View has been inflated.

Accessing the Activity from a Fragment

I'm trying to change the activity title from a fragment (in this case, it's an android.support.v4.app.Fragment). To this end, I save the activity in an attribute on the fragment when onAttach() is called on the fragment. According to the docs, onAttach() should be called before onCreateView(), which I'm using to request some data used to fill up the view. When I kick off the thread for the network retrieval, I want to indicate that in the title, so I'm trying to call this.activity.setTitle() from the Fragment. However, that keeps throwing a NullPointerException. What am I missing here?
You can access the Activity in a Fragment using getActivity(). It can be called safely as soon as onActivityCreated() was called on the Fragment. Before that, it might not be there or might not have been fully initialized yet.
If your thread starts before that, just note the fact somewhere in your Fragment and only change the title after onActivityCreated was called.
Nowadays you can call requiredActivity() too that return FragmentActivityobject and if fragment doesn't come from an Activity, method throws a IllegalStateException

What's the difference between detaching a Fragment and removing it?

In the Android docs for a FragmentTransaction I noticed two very similar methods: detach and remove. The descriptions over there don't seem to provide much insight about when to use each, and from what I can tell they appear to be the same.
So: what are the differences between these two methods?
The detach method removes the fragment from the UI, but its state is maintained by the Fragment Manager. This means you can reuse this fragment by calling the attach method, with a modified ViewHierarchy
Remove means the fragment instance cannot be re-attached. You will have to add it again to the fragment transaction.
Source Comment
You'll notice that when a Fragment is detached, its onPause, onStop and onDestroyView methods are called only (in that order). On the other hand, when a Fragment is removed, its onPause, onStop, onDestroyView, onDestroy and onDetach methods are called (in that order). Similarly, when attaching, the Fragment's onCreateView, onStart and onResume methods are called only; and when adding, the Fragment's onAttach, onCreate, onCreateView, onStart and onResume methods are called (in that order). – Adil Hussain
The naming of the fragment management methods are very confusing even according to Google engineers on message boards (see comments above). I made myself a little demo to figure out how things actually work. Here are my findings. Feel free to correct me if I am wrong.
To initially add a Fragment to an Activity, you use:
getFragmentManager().beginTransaction().add(R.id.container, mFragment).commit().
This associates the Activity with the Fragment and also associates a View with the Fragment.
Here are the resulting life cycle events and other important method return values:
onAttach()
onCreate()
onCreateView()
onViewCreated()
onActivityCreated()
onViewStateRestored()
onStart()
onResume()
mFragment.getView() == null: false
mFragment.getActivity() == null: false
To remove a Fragment from an Activity, you use:
getFragmentManager().beginTransaction().remove(mFragment).commit().
This removes any association with a View or to an Activity.
Here are the resulting life cycle events and other important method return values:
onPause()
onStop()
onDestroyView()
onDestroy()
onDetach()
mFragment.getView() == null: true
mFragment.getActivity() == null: true
I re-added the fragment here
To detach an added Fragment from an Activity, you use:
getFragmentManager().beginTransaction().detach(mFragment).commit().
This removes any association with a View, but keeps the association with the Activity.
Here are the resulting life cycle events and other important method return values:
onPause()
onStop()
onDestroyView()
mFragment.getView() == null: true
mFragment.getActivity() == null: false
To re-attach a Fragment that was detached to the Activity, you use:
getFragmentManager().beginTransaction().attach(mFragment).commit().
This creates a new View to associate with the Fragment and maintains the Activity association.
Here are the resulting life cycle events and other important method return values:
onCreateView()
onViewCreated()
onActivityCreated()
onViewStateRestored()
onStart()
onResume()
mFragment.getView() == null: false
mFragment.getActivity() == null: false
Other important things to note:
If you detach a Fragment and then try to add it again using add() rather than attach(), nothing seems to change.
if you attempt to add a Fragment that has been removed using remove() by using attach() rather than add(), nothing seems to change.
When getView() returns null, the Fragment may still have internal references to the last View it created. This View is no longer valid and should not be used.

Categories

Resources