public class WeekAdapter extends ArrayAdapter {
private int resource;
private LayoutInflater layoutInflater;
private String[] week = new String[]{};
public WeekAdapter(Context context, int resource, String[] objects) {
super(context, resource, objects);
this.resource = resource;
this.week = objects;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = layoutInflater.inflate(resource, null);
holder.ivlogo = (LetterImageView) convertView.findViewById(R.id.ivLetter);
holder.tvWeek = (TextView) convertView.findViewById(R.id.tvmain);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ivlogo.setOval(true);
holder.ivlogo.setLetter(week[position].charAt(0));
holder.tvWeek.setText(week[position]);
return convertView;
}
class ViewHolder {
private LetterImageView ivlogo;
private TextView tvWeek;
}
}
我正在尝试制作时间表。但每当我点击列表时,我的应用程序崩溃了。它说:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.admin.ttabledemo.Utils.LetterImageView.setOval(boolean)' on a null object reference
at com.example.admin.ttabledemo.WeekActivity$WeekAdapter.getView(WeekActivity.java:108)
我看过其他类似的问题,但我无法理解错误,因为我已经初始化了持有者对象。
答案 0 :(得分:1)
public class WeekAdapter extends ArrayAdapter {
private int resource;
private LayoutInflater layoutInflater;
private String[] week = new String[]{};
public WeekAdapter(Context context, int resource, String[] objects) {
super(context, resource, objects);
this.resource = resource;
this.week = objects;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = layoutInflater.inflate(resource, null);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ivlogo = (LetterImageView) convertView.findViewById(R.id.ivLetter);
holder.tvWeek = (TextView) convertView.findViewById(R.id.tvmain);
holder.ivlogo.setOval(true);
holder.ivlogo.setLetter(week[position].charAt(0));
holder.tvWeek.setText(week[position]);
return convertView;
}
class ViewHolder {
private LetterImageView ivlogo;
private TextView tvWeek;
}
}
这样做..(我已将holder.ivlogo
和holder.tvweek
的分配转移到if-else语句之外。