如何在列表视图中使用 Baseadapter?为什么会出现 Null 点异常?

How to use Baseadapter in a listview?Why i am getting Null point exception?

我尝试使用 baseadapter.I 将元素插入到列表视图中 想将菜单插入到 listview.I 已使用适配器数据集适配器将行膨胀到列表视图中,但我得到的是空指针此行的异常-row = inflater.inflate(R.layout.menu_detail, parent,false);

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

DataSetAdapter.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;
}


}

menu_detail.java

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:gravity="center"
    android:background="#5ba4e5"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="8pt"
        android:textColor="#000000"
        android:layout_gravity="center"
        android:id="@+id/detail"/>

</LinearLayout>

你得到 NullPointerException 因为当调用 getCountmenuitems 为空。更改

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 应该 return 位置的项目。您现在没有使用它,但您将来可能会使用它:

@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);
}

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