安卓setText(java.lang.CharSequence) on a null object reference解决办法

来源:互联网 发布:getdata软件 编辑:程序博客网 时间:2024/06/05 06:38


Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference


故障出现的现象:

在一个Fragment的前面声明了全局变量 

private TextView textViewTodayTemp;
在onActivityCreated()

却又声明了局部变量并关联:

TextView  textViewTodayTemp = ( TextView)getActivity().findViewById(R.id.textViewTodayTemp);
然后在别的方法中调用:
textViewTodayTemp.setText()
导致出现错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

故障解决办法:

onActivityCreated()中,不用声明局部变量,去掉前面的TextView,改为:

 textViewTodayTemp = ( TextView)getActivity().findViewById(R.id.textViewTodayTemp);

这样故障解决。
















阅读全文
0 0