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

《第一行代码》中最后天气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
}

你可能感兴趣的:(Android知识自学)