问题
I have my listview working to display it on the MainActivity and the layout is set to have 3 TextView properties of a new Person object.
My previous code was working but the scrolling was slow, so i looked into using the Holder pattern for optimization. However, when trying to implement this i am getting NullPointerException
on lines TextView personID=(TextView) view.findViewById(R.id.person_field1)
listView is set to a ListView on the MainActivity and i need the person objects to display on this view within the MainActivity.
MainActivity class:
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;
}
}
回答1:
because there really is null
pay attention to check view == null
, and then view
never initialized
try this
view = layoutInflator.inflate(R.layout.list_layout, null);
回答2:
Just add reference to your view:
view = layoutInflator.inflate(R.layout.list_layout, null);
回答3:
view
is null, you're even checking for it:
if (view == null) { ...
}
What you're missing is assigning the inflated layout to view
view = layoutInflator.inflate(R.layout.list_layout, null);
来源:https://stackoverflow.com/questions/28730417/making-a-listview-holder-for-mainactivity