Why is my context in my Fragment null?

前端 未结 4 1327
耶瑟儿~
耶瑟儿~ 2020-12-07 01:04

I have got a question regarding the usage of context in a fragment. My problem is that I always get a NullpointerException. Here is what i do:

Create a class that ex

相关标签:
4条回答
  • 2020-12-07 01:55

    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);
        }
    } 
    
    0 讨论(0)
  • 2020-12-07 02:05

    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());
      }
    
    0 讨论(0)
  • 2020-12-07 02:07

    Hi the question has answered, but generally if you want to get context in fragment or dialogFragment use this

    protected lateinit var baseActivity: BaseActivity
    protected lateinit var contextFragment: Context
    
    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is BaseActivity) {
            this.baseActivity = context
        }
        this.contextFragment = context
    }
    

    and in java

     protected BaseActivity baseActivity;
     protected Context context;
    
     @Override
     public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.context = context;
        if (context instanceof BaseActivity) {
            this.baseActivity = (BaseActivity) context;
        }
    }
    
    0 讨论(0)
  • 2020-12-07 02:10

    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().

    0 讨论(0)
提交回复
热议问题