Trying to display a list of contacts using a Custom Array Adapter. However every time I run my application I get the following error:
java.lang.NullPointerException at com.example.contactsapp.ContactsListAdapter.getView(ContactsListAdapter.java:37)
This is my Custom List Adapter class:
public class ContactsListAdapter extends ArrayAdapter<Contact> {
List <Contact> people;
//Contact c;
TextView name;
TextView email;
public ContactsListAdapter(Context context, List<Contact> people) {
super(context, R.layout.list_row, people);
this.people = people;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.list_row, null);
}
Contact c = this.people.get(position);
name = (TextView)v.findViewById(R.id.namebox);
name.setText(c.getName());
email = (TextView)v.findViewById(R.id.emailbox);
email.setText(c.getEmail());
return v;
}
}
This is my ListView activity:
public class ViewContacts extends ListActivity{
List <Contact> people;
ContactsListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_view);
createTestData();
adapter = new ContactsListAdapter(this, people);
this.setListAdapter(adapter);
}
public void createTestData(){
people = new ArrayList<Contact>();
people.add(new Contact("Jack", "jc@hotmail.com"));
people.add(new Contact("Jack", "jc@hotmail.com"));
people.add(new Contact("Jack", "jc@hotmail.com"));
people.add(new Contact("Jack", "jc@hotmail.com"));
people.add(new Contact("Jack", "jc@hotmail.com"));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Contact c = (Contact)people.get(position);
Toast.makeText(v.getContext(), c.getName().toString() + " Clicked!", Toast.LENGTH_SHORT).show();
}
}
Any ideas?
(My basic assumption without seeing your logcat errors)
Because of you forgot
something like,
You are inflating view but not assign it to
View v. That’s why you are gettingNullPointerExceptiononnameandemailTextViews.