我为ListView
设置了自定义适配器。它在NullPointerException
给了我setAdapter
。我已经多次查看了我的代码,无法弄清楚导致NPE的原因。以下是相关的代码段:
活动:
ListView mListView;
Vector<DashboardBean> dashboardBean= new Vector<DashboardBean>();
MyCustomAdapter adapter;
adapter = new MyCustomAdapter(MyDashboardActivity.this,
R.layout.testdashboard_row, dashboardBean);
adapter.clear();
dashboardBean.add(new DashboardBean(projects, workRequests, status));
mListView.setAdapter(adapter);
Dashboardbean:
public class DashboardBean {
public String project;
public String workRequest;
public String startDate;
public String status;
public String actualHours;
public String actualMins;
public DashboardBean(String project, String workRequest,String status)
{
this.project = project;
this.workRequest = workRequest;
this.status = status;
}
}
CustomAdapter:
public class MyCustomAdapter extends ArrayAdapter<DashboardBean> {
Context context;
int layoutResourceId;
DashboardBean currentMRB;
Vector<DashboardBean> data;
public MyCustomAdapter(Context context, int layoutResourceId, Vector<DashboardBean> data)
{
super(context,layoutResourceId,data);
this.layoutResourceId = layoutResourceId;
this.context=context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyStringReaderHolder holder;
if(row==null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent,false);
holder= new MyStringReaderHolder();
holder.project = (TextView)row.findViewById(R.id.project);
holder.workRequest = (TextView)row.findViewById(R.id.work_request);
holder.status = (TextView) row.findViewById(R.id.status);
row.setTag(holder);
}
else
{
holder=(MyStringReaderHolder) row.getTag();
}
DashboardBean mrb = data.elementAt(position);
holder.project.setText(mrb.project);
holder.workRequest.setText(mrb.workRequest);
holder.status.setText(mrb.status);
return row;
}
static class MyStringReaderHolder
{
TextView project, workRequest, startDate, status, actualHours;
}
}
有人可以帮忙吗?
答案 0 :(得分:3)
在“活动”代码段中,您永远不会为mListView
分配值:
ListView mListView; //initialize me please :)
因此,它为null,并且总是抛出NullPointerException
。也许您在xml中定义了一些内容,并且您希望调用findViewById(int)
。
mListView = (ListView) findViewById(R.id.theListViewId);