如何在Android中设置适配器中的文本?

时间:2015-07-26 13:11:39

标签: android nullpointerexception adapter

我不知道如何在TextView方法中将文字设置为getView()。如果我把它留在那里,它将导致NullPointerException。我试过一个日志,它打印了很多次。

PS:显然,我确定该变量包含一个有效的字符串。

public class DayAdapter extends BaseAdapter {

    SharedPreferences mSharedPreferences;

    private Context mContext;
    private Day[] mDays;
    private String mCity;
    private String mAdminArea;

    public DayAdapter(Context context, Day[] days, String city, String adminArea) {
        mContext = context;
        mDays = days;
        mCity = city;
        mAdminArea = adminArea;
    }

    @Override
    public int getCount() {
        return mDays.length;
    }

    @Override
    public Object getItem(int position) {
        return mDays[position];
    }

    @Override
    public long getItemId(int position) {
        return 0; // we aren't going to use this. Tag items for easy reference
    }

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

        if (convertView == null) {
            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);
            holder.locationLabel = (TextView) convertView.findViewById(R.id.locationLabel);

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

        Day day = mDays[position];

        holder.iconImageView.setImageResource(day.getIconId());

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

        Log.d(DayAdapter.class.getSimpleName(), mCity); // this is called many times 

        holder.locationLabel.setText(mCity); // this cause the error





        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;
        TextView locationLabel;
    }
}

0 个答案:

没有答案