setText时的空指针异常 - TextView [复制]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了setText时的空指针异常 - TextView [复制]相关的知识,希望对你有一定的参考价值。

这个问题在这里已有答案:

我在MainActivity中有一个片段并尝试在片段中设置setText,但是当我尝试这样做时,我得到Null Pointer Exception。我检查了拼写,但似乎没问题。我调试应用程序并检查这些变量,但似乎它们都是null。

异常出现在clearText()方法的第一行。

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_sun, container, false);

        sunRiseTime = v.findViewById(R.id.sunRiseTime);
        sunRiseAzimuth = v.findViewById(R.id.sunRiseAzimuth);
        sunSetTime = v.findViewById(R.id.sunSetTime);
        sunSetAzimuth = v.findViewById(R.id.sunSetAzimuth);
        duskTime = v.findViewById(R.id.duskTime);
        dawnTime = v.findViewById(R.id.dawnTime);

        return v;
    }

private void clearText(){
        sunSetTime.setText("");
        sunSetAzimuth.setText("");
        sunRiseTime.setText("");
        sunRiseAzimuth.setText("");
        duskTime.setText("");
        dawnTime.setText("");
    }

错误

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                       at com.example.mariusz.astroweather.SunFragment.clearText(SunFragment.java:99)
答案

检查并跟踪onCreateView()内部,看看sunSetTime TextView是否为空。可能会发生R.layout.fragment_sun的替代布局,可能不包括sunSetTime TextView。如果不是这种情况,可能会在onCreateView之前调用clearText()。

以上是关于setText时的空指针异常 - TextView [复制]的主要内容,如果未能解决你的问题,请参考以下文章

FragmentPagerAdapter加载fragment并使用setUserVisibleHint()处理预加载时遇到的坑,给textview赋值时出现的空指针异常

尝试在 recyclerview kotlin 上的空对象引用上调用虚拟方法 'void android.widget.TextView.setText(java.lang.CharSequence)

获得额外意图时的空指针

发送 json 数据时的空指针

从 Android 的 LocationManager 请求 getLastKnownLocation 时的空指针

在 Spring Boot 2 中测试组件时的空指针