简体   繁体   中英

Is it necessary to check if parent activity is null in fragment onActivityCreated method?

I'm reading the following tutorial in which the author is showing how to implement a tab interface using fragments. Each of the fragments has a null check for the parent activity before setting a list adapter like this:

public class LocationListFragment extends ListFragment {

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Activity activity = getActivity();

        if (activity != null) {            
           ListAdapter listAdapter = new LocationModelListAdapter(activity, FragmentTabTutorialApplication.sLocations);
           setListAdapter(listAdapter);
        }
    }
}

I'm trying to get a better understanding of the relationship between the activity and fragment lifecycles, so my question is: why is necessary to do this? The docs says that the onActivityCreated method is called after the onCreate method of the activity returns, if this is the case, how the activity can be null at this point?

I don't think you need to check it on this particular override. The fragment lifecycle is heavily intertwined with its hosting activity.

I think most people check the getActivity() != null as good practice since it can be null and crash your app if you're calling it as a result of a handler/asyncTask when the fragment itself has been detached from the activity and as such, the getActivity() returns null.

On your main (UI) thread (which is where onActivityCreated() is called) it should not happen though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM