Attempt to invoke virtual method ' 'on a null object reference

前端 未结 5 795
一个人的身影
一个人的身影 2020-12-22 05:37

I am getting the following error

Attempt to invoke virtual method \'void android.widget.StackView.setAdapter(android.widget.Adapter)\' on a null

相关标签:
5条回答
  • 2020-12-22 05:58

    You are doing:

    stackView = (StackView) getActivity().findViewById(R.id.stackView1);
    

    Your stackView is null. getActivity().findViewById returns null.

    Why are you using getActivity()?

    Where is the stackView? You should load it from the right xml.

    as @Tauqir mentioned, you need to inflate the right xml like this:

    View view = inflater.inflate(R.layout.events_layout, null);
    stackView = (StackView) view.findViewById(R.id.stackView1);
    return view;
    
    0 讨论(0)
  • 2020-12-22 06:00

    R.id.stackView1 is not found when you try to assign stackView, so it is null

    0 讨论(0)
  • 2020-12-22 06:01

    Try this inside onCreateView

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
            View view = inflater.inflate(R.layout.events_layout, null);
    
            -------------some codes ------------
    
            stackView = (StackView) view.findViewById(R.id.stackView1);
    
            -------------some codes ------------
            return view;
    
        }
    
    0 讨论(0)
  • 2020-12-22 06:04

    Do this

    View rootView = inflater.inflate(R.layout.events, container, false);
    stackView = (StackView) rootview.findViewById(R.id.stackView1);
    .
    .
    .
    return rootview
    

    You first need to inflate the layout and call findViewById() on the View it returns, thus getActivity().findViewById should be rootView.findViewByID.

    There are some other issues with your code as well. Like getctivity().getApplicationContext, just getActivity() is fine.

    0 讨论(0)
  • 2020-12-22 06:13

    change container and false to null

    Do this:

    View rootView = inflater.inflate(R.layout.events, null);
    
    0 讨论(0)
提交回复
热议问题