自定义 Adapter 的 getView() 中的空指针异常
Posted
技术标签:
【中文标题】自定义 Adapter 的 getView() 中的空指针异常【英文标题】:Null pointer exception in getView() of custom Adapter 【发布时间】:2012-08-01 06:58:06 【问题描述】:我正在为我的 ListView 使用这个自定义适配器:
public class SideMenuAdapter extends BaseAdapter
private static final int TYPE_MAX_COUNT = 2;
private static LayoutInflater inflater = null;
private Activity activity;
public static String[] values;
ListView myList;
public SideMenuAdapter(Activity a, String[] sa, ListView lv)
values = sa;
activity = a;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myList = lv;
public int getCount()
return values.length;
public Object getItem(int position)
return position;
public long getItemId(int position)
return position;
public static class ViewHolder
public TextView mainText;
public TextView sideText;
public View getView(int position, View convertView, ViewGroup parent)
ViewHolder holder = new ViewHolder();
View vi = convertView;
if (vi == null)
//here i am getting NullPointerException
vi.setTag(holder);
else
holder = (ViewHolder) vi.getTag();
vi = inflater.inflate(R.layout.side_menu_list_item, null);
holder.mainText = (TextView) vi.findViewById(R.id.mainText_sideMenu);
holder.sideText = (TextView) vi.findViewById(R.id.sideText_sideMenu);
holder.mainText.setText(values[position]);
if(position == 2)
holder.sideText.setText("3");
holder.sideText.setBackgroundResource(R.drawable.orange);
return convertView;
@Override
public int getViewTypeCount()
return TYPE_MAX_COUNT;
我正在以这种方式将适配器设置为我的列表视图:
String menuItems[] = new String[] "My Wants", "Profile", "Notifications",
"Feedback", "Logout" ;
listView1.setAdapter(new SideMenuAdapter(this, menuItems, listView1));
我哪里错了??
【问题讨论】:
【参考方案1】:你应该在你的vi.setTag(holder);
之前初始化vi
【讨论】:
到我用于 ListView 项目的布局?? 是的。这是使用自定义 BaseAdapter thinkandroid.wordpress.com/2010/01/13/custom-baseadapters 的示例【参考方案2】:试试这个,可能对你有帮助...
public View getView(int position, @Nullable View convertView, ViewGroup parent)
ViewHolder holder = new ViewHolder();
View vi = convertView;
if (vi == null)
LayoutInflater inflater = ((Activity)activity).getLayoutInflater();
vi = inflater.inflate(R.layout.side_menu_list_item, null);
holder.mainText = (TextView) vi.findViewById(R.id.mainText_sideMenu);
holder.sideText = (TextView) vi.findViewById(R.id.sideText_sideMenu);
vi.setTag(holder);
else
holder = (ViewHolder) vi.getTag();
holder.mainText.setText(values[position]);
if(position == 2)
holder.sideText.setText("3");
holder.sideText.setBackgroundResource(R.drawable.orange);
return convertView;
【讨论】:
耶... :) 这对我有帮助:***.com/questions/12590342/…以上是关于自定义 Adapter 的 getView() 中的空指针异常的主要内容,如果未能解决你的问题,请参考以下文章
1.0 listview的adapter中getview的三种写法