如何在列表视图中使用Baseadapter?为什么我得到Null点异常?

时间:2015-04-02 09:23:14

标签: android android-listview baseadapter

我尝试使用baseadapter将元素插入到listview中。我想将菜单插入到listview中。我使用了一个adapter-DatasetAdapter将行膨胀到listview中,但是我在此行获得了空指针异常 - { {1}}

row = inflater.inflate(R.layout.menu_detail, parent,false);

DataSetAdapter.java

DatasetAdapter adapter=new DatasetAdapter(this,menu);
        dList.setAdapter(adapter);
menu = new String[]{"Feedback","Help","Tour","Sign in/Sign up"};

menu_detail.java

public class DatasetAdapter extends BaseAdapter  {


private Context context;
private String[] menuitems;

LayoutInflater inflater;

public DatasetAdapter(Context cont, String[] menu) {
    this.context=cont;
    this.menuitems=menu;

}

@Override
public int getCount() {
    // TODO Auto-generated method stub

    return menuitems.length;
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public long getItemId(int arg0) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    View row = convertView;

    if (row == null)
        row = inflater.inflate(R.layout.menu_detail, parent,false);

    TextView titlerow = (TextView) row.findViewById(R.id.detail);

    return row;
}


}

1 个答案:

答案 0 :(得分:1)

您获得NullPointerException,因为menuitems在调用getCount时为空。改变

DatasetAdapter adapter=new DatasetAdapter(this,menu);
dList.setAdapter(adapter);
menu = new String[]{"Feedback","Help","Tour","Sign in/Sign up"};

menu = new String[]{"Feedback","Help","Tour","Sign in/Sign up"};
DatasetAdapter adapter=new DatasetAdapter(this,menu);
dList.setAdapter(adapter);

您的getItem应该返回该位置的项目。你现在没有使用它,但你可能会在将来使用它:

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

在您的构造函数中,您永远不会初始化inflater

public DatasetAdapter(Context cont, String[] menu) {
    this.context=cont;
    this.menuitems=menu;
    inflater = LayoutInflater.from(cont);
}

并且您可以避免保留对上下文的引用,因为您没有在任何地方使用它