Why is my context in my Fragment null?

回眸只為那壹抹淺笑 提交于 2019-11-28 01:51:37

You're attempting to get a Context when the Fragment is first instantiated. At that time, it is NOT attached to an Activity, so there is no valid Context.

Have a look at the Fragment Lifecycle. Everything between onAttach() to onDetach() contain a reference to a valid Context instance. This Context instance is usually retrieved via getActivity()

Code example:

private Helper mHelper;

@Override
public void onAttach(Activity activity){
   super.onAttach (activity);
   mHelper = new Helper (activity);
}

I used onAttach() in my example, @LaurenceDawson used onActivityCreated(). Note the differences. Since onAttach() gets an Activity passed to it already, I didn't use getActivity(). Instead I used the argument passed. For all other methods in the lifecycle, you will have to use getActivity().

When are you instantiating your Helper class? Make sure it's after onActivityCreated() in the lifecycle of the Fragment.

http://developer.android.com/images/fragment_lifecycle.png

The following code should work:

@Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    helper = new Helper(getActivity());
  }

getActivity() can return null if it gets called before onAttach() gets called. I would recommend something like this:

public class Fragment extends SherlockFragment { 

    private Helper helper;

    // Other code

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        helper = new Helper(activity);
    }
} 

I had the same problem after migrating from android.support to androidx. The problem was a bug in androidx library, described here: https://issuetracker.google.com/issues/119256498

Solution:

// Crashing:
implementation "androidx.appcompat:appcompat:1.1.0-alpha01"

// Working:
implementation "androidx.appcompat:appcompat:1.1.0-alpha03"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!