setText - TextView时出现空指针异常

时间:2018-03-04 17:53:50

标签: android nullpointerexception

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

异常出现在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)

1 个答案:

答案 0 :(得分:0)

检查并跟踪onCreateView()内部,看看sunSetTime TextView是否为空。您可能会遇到R.layout.fragment_sun的备用布局,其中可能不包含sunSetTime TextView。 如果不是这种情况,可能会在onCreateView之前调用clearText()。

相关问题