我哪里错了? 为什么这个空指针异常
private class GridAdapter extends BaseAdapter {
private LayoutInflater inflater;
public GridAdapter(Context context) {
Logger.d(TAG, "GridAdapter");
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
Logger.d("SIZE",""+AppConstants.getMenuList().size());
return AppConstants.getMenuList().size();
}
@Override
public Object getItem(int i) {
return AppConstants.getMenuList().get(i);
}
@Override
public long getItemId(int i) {
return i;
}
class ViewHolder {
TextView title;
RelativeLayout layout;
ImageView image;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = inflater.inflate(R.layout.inflater_grid_layout, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.layout = (RelativeLayout) view.findViewById(R.id.igl_layout);
viewHolder.title = (TextView) view.findViewById(R.id.igl_name);
viewHolder.image = (ImageView) view.findViewById(R.id.igl_image);
view.setTag(viewHolder);
} else {
view = convertView;
}
final ViewHolder holder = (ViewHolder) view.getTag();
MenuModel item = (MenuModel) getItem(position);
holder.layout.setBackgroundColor(item.getColor()); //NULL POINTER HERE
holder.title.setText(item.getName());
holder.image.setImageResource(item.getImage());
return view;
}
}
这是我的LogCat:
显示java.lang.NullPointerException 在in.abm.indiape.fragments.GridMenuScreen $ GridAdapter.getView(GridMenuScreen.java:115) 在android.widget.AbsListView.obtainView(AbsListView.java:2624) 在android.widget.GridView.onMeasure(GridView.java:1045) 在android.view.View.measure(View.java:16831) 在android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728) 在android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477) 在android.view.View.measure(View.java:16831)
答案 0 :(得分:1)
您setTag
不能查看convertView
。在else部分,您有view = convertView;
。
然后你有view.getTag()
当convertView
不为null时,可能会返回null,如prosper k所示。
您无需使用View view
即可直接使用convertView
。
所以将getView
更改为
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView= inflater.inflate(R.layout.inflater_grid_layout, null);
viewHolder = new ViewHolder();
viewHolder.layout = (RelativeLayout) convertView.findViewById(R.id.igl_layout);
viewHolder.title = (TextView) convertView.findViewById(R.id.igl_name);
viewHolder.image = (ImageView) convertView.findViewById(R.id.igl_image);
convertView.setTag(viewHolder); // setTag if convertView is null
} else {
viewHolder = (ViewHolder)convertView.getTag();
// get tag if convertView is not null
}
MenuModel item = (MenuModel) getItem(position);
// update ui elements
viewHolder.layout.setBackgroundColor(item.getColor());
viewHolder.title.setText(item.getName());
viewHolder.image.setImageResource(item.getImage());
return convertView;
}