Why is onAttach called before onCreate?

Solution 1:

TL;DR:

In order to not break the design consistency amongst different UI components in android,the onCreate() method will have similar functionality across all of them.

When linking Containers to Contents like Window to Activity and Activity to Fragment a preliminary check needs to be done to determine the state of container. And that explains the use and position of onAttach() in the fragment lifecycle.

Too short;Need longer:

The answer is in the archetype code itself,

@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

Another example would be in Jake Wharton's ActionBarSherlock library.

Why would you want to use a method like onCreate() which is has the same purpose in an activity ,service.

The onCreate() is meant to handle issues with respect to that particular context creation.It does not make sense if onCreate() is used to check the state of its container.

The second reason that I can come determine is that a fragment is designed to be activity independent.The onAttach() provides an interface to determine the state/type/(other detail that matters to the fragment) of the containing activity with reference to the fragment before you initialize a fragment.

EDIT:

An activity exists independently and therefore has a self sustaining lifecycle.

for a fragment :

  1. The independent lifecycle components(same as any other components):

    • onCreate()
    • onStart()
    • onResume()
    • onPause()
    • onStop()
    • onDestroy()
  2. The interaction based components:

    • onAttach()
    • onCreateView()
    • onActivityCreated()
    • onDestroyView()
    • onDetach()

from the documentation:

The flow of a fragment's lifecycle, as it is affected by its host activity, (...) each successive state of the activity determines which callback methods a fragment may receive. For example, when the activity has received its onCreate() callback, a fragment in the activity receives no more than the onActivityCreated() callback.

Once the activity reaches the resumed state, you can freely add and remove fragments to the activity. Thus, only while the activity is in the resumed state can the lifecycle of a fragment change independently.

However, when the activity leaves the resumed state, the fragment again is pushed through its lifecycle by the activity.

answering another question which came up in the comments:

Caution: If you need a Context object within your Fragment, you can call getActivity(). However, be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null.

The design philosophy states that a Fragment is designed for reuse. A fragment (by design) could(and should) be used across multiple activities.

The onCreate by definition is responsible to create a fragment. Consider the case of orientation,your fragment could be: - using different layouts in different orientations. - applicable only in portrait orientation and not landscape - To be used only on tables and mobile phones.

All these situations would require a check before the fragment is initialized from the android perspective(onCreate()) and the view inflated(onCreateView()).

Also consider the situation of a headless fragment.The onAttach() provides you the interface required for preliminary checks.

Solution 2:

Because onAttach() assigns hosting activity to the Fragment. If it had been called after onCreate() then there would be no context for your fragment (getActivity() would return null) and you would not be able to do anything in onCreate() method without that context anyway.

Another fitting reason is that Fragment's lifecycle is similar to Activity's lifecycle. In Activity.onAttach() activity gets attached to its parent (a window). Similarly in Fragment.onAttach() fragment gets attached to its parent (an activity), before any other initialization is done.

Solution 3:

This is related to retained fragments. Following Fragment setRetainInstance(boolean retain) documentation:

If set, the fragment lifecycle will be slightly different when an activity is recreated:

  • onDestroy() will not be called (but onDetach() still will be, because the fragment is being detached from its current activity).
  • onCreate(Bundle) will not be called since the fragment is not being re-created.
  • onAttach(Activity) and onActivityCreated(Bundle) will still be called.

Take a look at the source code (android.support.v4.app.FragmentManager, v21):

void moveToState(Fragment f, 
                 int newState, 
                 int transit, 
                 int transitionStyle,
                 boolean keepActive) {
    ...
    f.onAttach(mActivity);
    if (!f.mCalled) {
        throw new SuperNotCalledException("Fragment " + f
                + " did not call through to super.onAttach()");
    }
    if (f.mParentFragment == null) {
        mActivity.onAttachFragment(f);
    }

    if (!f.mRetaining) {
        f.performCreate(f.mSavedFragmentState); // <- Here onCreate() will be called
    }
    ...
}

Example

Case 1: not retained fragment or setRetainInstanceState(false)

Application is started. Fragment is added dynamically using FragmentManager or inflated from XML via setContentView().

onAttach() called after Activity super.onCreate() call - Activity is already initialised.

MainActivity﹕ call super.onCreate() before
MainActivity﹕ super.onCreate() returned
MainFragment﹕ onAttach() getActivity=com.example.MainActivity@1be4f2dd
MainFragment﹕ onCreate() getActivity=com.example.MainActivity@1be4f2dd

Configuration changed. Activity recreates fragments from saved state, fragments are added/attached from inside Activity super.onCreate() call:

MainActivity﹕ call super.onCreate() before
MainFragment﹕ onAttach() getActivity=com.example.MainActivity@2443d905
MainFragment﹕ onCreate() getActivity=com.example.MainActivity@2443d905
MainActivity﹕ super.onCreate() returned

Case 2: setRetainsInstanceState(true)

Application is started. Fragment is added dynamically using FragmentManager or inflated from XML via setContentView(). Same as above:

onAttach() called after Activity super.onCreate() call - Activity is already initialised.

MainActivity﹕ call super.onCreate() before
MainActivity﹕ super.onCreate() returned
MainFragment﹕ onAttach() getActivity=com.example.MainActivity@3d54a168
MainFragment﹕ onCreate() getActivity=com.example.MainActivity@3d54a168

Configuration changed.

Fragment onCreate() not called, but onAttach() still called - you need to know, that hosting Activity has changed. But still fragment is already created, so no onCreate() called.

MainActivity﹕ call super.onCreate() before
MainFragment﹕ onAttach() getActivity=com.example.MainActivity@d7b283e
MainActivity﹕ super.onCreate() returned