0

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", "[email protected]"));
        people.add(new Contact("Jack", "[email protected]"));
        people.add(new Contact("Jack", "[email protected]"));
        people.add(new Contact("Jack", "[email protected]"));
        people.add(new Contact("Jack", "[email protected]"));
 }

@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?

1
  • 1
    can you point out what is line 37? Commented Jan 17, 2013 at 19:39

1 Answer 1

1

(My basic assumption without seeing your logcat errors)

Because of you forgot

v = inflater.inflate(R.layout.list_row, null);

something like,

View v = convertView;

    if(v == null){
        LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.list_row, null);
    }

You are inflating view but not assign it to View v. That's why you are getting NullPointerException on name and email TextViews.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.