java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTe

来源:互联网 发布:JAVA远程连接db2数据库 编辑:程序博客网 时间:2024/05/17 13:43

《第一行代码》中最后天气App的问题之----NullPointerException

关于空指针异常的问题,我准备遇到一次就把它写在这里一次!

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

错误原因是:

    TextView dateText = (TextView) findViewById(R.id.date_text);    TextView infoText = (TextView) findViewById(R.id.info_text);    TextView maxText = (TextView)  findViewById(R.id.max_text);    TextView minText = (TextView)  findViewById(R.id.min_text);
定位布局里面的控件时忘加 view.  了!!!

修改后的代码:

for (Forecast forecast : weather.forecastList) {    View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false);    TextView dateText = (TextView) view.findViewById(R.id.date_text);    TextView infoText = (TextView) view.findViewById(R.id.info_text);    TextView maxText = (TextView) view.findViewById(R.id.max_text);    TextView minText = (TextView) view.findViewById(R.id.min_text);    dateText.setText(forecast.date);    infoText.setText(forecast.more.info);    maxText.setText(forecast.temperature.max);    minText.setText(forecast.temperature.min);    forecastLayout.addView(view);//手动添加到父布局(root)中,因为inflate()第三个参数是false}

1 0
原创粉丝点击