在TextView上显示数字时出现NullException

时间:2016-03-17 14:00:56

标签: android listview

当我想在列表视图上显示数据时,我得到Null。 日志告诉问题出在这一行:

holder.temperatureLabel.setText(day.getTemperatureMax()+ "");

结束那是错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                        at com.example.hay.stormy.adapters.DayAdapter.getView(DayAdapter.java:64)

我还试图给出一个常数或一个常量字符串,它仍然会出现同样的错误,但如果我运行没有这一行的应用程序,我会得到其他需要的数据,很奇怪... < / p>

一些代码供你理解:

我的ViewHolder和getView:

   public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    if (convertView == null) {
        // brand new
        convertView = LayoutInflater.from(mContext).inflate(R.layout.daily_list_item, null);
        holder = new ViewHolder();
        holder.iconImageView = (ImageView) convertView.findViewById(R.id.iconImageView);
        holder.temperatureLabel = (TextView) convertView.findViewById(R.id.temperatureLabel);
        holder.dayLabel = (TextView) convertView.findViewById(R.id.dayNameLabel);

        convertView.setTag(holder);
    }
    else {
        holder = (ViewHolder) convertView.getTag();
    }

    Day day = mDays[position];

    holder.iconImageView.setImageResource(day.getIconId());
    holder.temperatureLabel.setText(day.getTemperatureMax()+ "");

    if (position == 0) {
        holder.dayLabel.setText("Today");
    }
    else {
        holder.dayLabel.setText(day.getDayOfTheWeek());
    }

    return convertView;
}

private static class ViewHolder {
    ImageView iconImageView; // public by default
    TextView temperatureLabel;
    TextView dayLabel;
}

和我在Day类中有问题参数的getter和setter:

public int getTemperatureMax() {
    return (int)Math.round(mTemperatureMax);
}

public void setTemperatureMax(double temperatureMax) {
    mTemperatureMax = temperatureMax;
}

1 个答案:

答案 0 :(得分:3)

似乎temperatureLabel为空。您可能设置了错误的ID。如果找不到视图,则findViewById返回null。 http://developer.android.com/reference/android/view/View.html#findViewById(int)