Why getContext() in fragment sometimes returns null?

As the accepted answer says, you must look into the way you are using and caching context. Somehow you are leaking context that is causing Null Pointer Exception.


Below Answer is as per the first revision of the question.

Use onAttach() to get Context. Most of the cases, you don’t need this solution so use this solution only if any other solution does not work. And you may create a chance to activity leak, so be cleaver while using it. You may require to make context null again when you leave from fragment

// Declare Context variable at class level in Fragment
private Context mContext;

// Initialise it from onAttach()
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mContext = context;
}

This context will be available in onCreateView, so You should use it.


From Fragment Documentation

Caution: If you need a Context object within your Fragment, you can call getContext(). However, be careful to call getContext() 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,
getContext() will return null.

Leave a Comment