How do you end up with a null pointer like Fragment's ViewPager?

find other solutions on the Internet
error log:
java.lang.NullPointerException: Attempt to invoke virtual method "android.view.View android.app.Activity.findViewById (int)" on a null object reference at com.dmxy.fragment.ChannelFragment.onCheckedChanged (ChannelFragment.java:226)

Code:

  @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (json != null) {
            Gson gson = new Gson();
            ChannelGameTypeBean channelGameTypeBean = gson.fromJson(json, ChannelGameTypeBean.class);
            List<ChannelGameTypeBean.DataBean> data = channelGameTypeBean.getData();
            //TODO:
            ChannelGameTypeBean.DataBean dataBean = data.get(0);//  1.  2.   3.
            List<ChannelGameTypeBean.DataBean.NavBean> nav = dataBean.getNav();
            ChannelGameTypeBean.DataBean.NavBean navBean = nav.get(checkedId);//0. 1.   2.    3.    4.
            int navId = navBean.getNavid();
            int sizes = data.size();
            String size = String.valueOf(sizes);
            //POST
            BaseApplication.getApplication().getMap().put("navId", navId);
            BaseApplication.getApplication().getMap().put("size", size);
        }
        // TODO 
        //TODO:bug
        RadioButton tempButton = getActivity().findViewById(checkedId); // 
        Log.d(TAG, "2222222222222");
        tempButton.setOnClickListener(this);
    }
Mar.03,2021

According to reason, the click action of RadioGroup should not occur in the case of getActivity () return null

p.s. In Fragment , it is incorrect to obtain the object of View directly through getActivity (). FindViewById (.) . It is correct to do this: Android Developer: Communicating with Other Fragments

.

there are two reasons why null pointers are generated here:
a) Fragment is assigned only after onCreateView. It is possible to get View
b) Fragment before that. OnDestroyView, has been called and View may be obtained after that

.

if you want to get a view correctly, make sure that the lifecycle executes accurately. In view of your situation, you should first determine whether the view obtained by Fragment's getView is empty, and if not, use getView (). FindViewById () to get the child View in Fragment. If you are in Activity, you can refer to the callback processing at the first answer position.

Menu