我让listview工作以在MainActivity上显示它,并且布局设置为具有新Person对象的3个TextView属性。
我以前的代码工作正常但滚动速度很慢,因此我研究了使用Holder模式进行优化。但是,在尝试实施此功能时,我会在NullPointerException
TextView personID=(TextView) view.findViewById(R.id.person_field1)
listView在MainActivity上设置为ListView,我需要在MainActivity中的此视图上显示person对象。
MainActivity类:
public void onButtonClick()
{
//put the persons objects on the listView within MainActivity
listView.setAdapter(new personAdapter(MainActivity.this, R.layout.list_layout,
personList));
}
class personAdapter extends ArrayAdapter<Person>
{
private LayoutInflater layoutInflator;
public personAdapter(Context context, int resource, List<Person> p) {
super(context, resource, p);
layoutInflator = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
Holder holder = null;
Person p = getItem(position);
if (view == null) {
layoutInflator.inflate(R.layout.list_layout, null);
//getting null pointer exceptions here
TextView personID = (TextView) view.findViewById(R.id.person_field1);
TextView personFName = (TextView) view.findViewById(R.id.person_field2);
TextView personLName = (TextView) view.findViewById(R.id.person_field3);
holder = new Holder(personID, personFName, personLName);
view.setTag(holder);
}
else {
holder = (Holder) view.getTag();
}
holder.stop.setText(person.getID());
holder.location.setText(person.getFName());
holder.time.setText(person.getLName());
return view;
}
}
static class Holder
{
public TextView id;
public TextView FName;
public TextView LName;
public Holder(TextView id, TextView FName, TextView LName) {
this.id = id;
this.FName = FName;
this.LName = LName;
}
}
答案 0 :(得分:2)
因为确实有空
注意检查view == null
,然后view
从未初始化
试试这个
view = layoutInflator.inflate(R.layout.list_layout, null);
答案 1 :(得分:1)
只需添加对您视图的引用:
view = layoutInflator.inflate(R.layout.list_layout, null);
答案 2 :(得分:1)
view
为空,您甚至会检查它:
if (view == null) { ...
}
您缺少的是将夸大的布局分配给view
view = layoutInflator.inflate(R.layout.list_layout, null);