0

尝试使用自定义阵列适配器显示联系人列表。但是,每次我运行我的应用程序时,都会出现以下错误:

com.example.contactsapp.ContactsListAdapter.getView 处的 java.lang.NullPointerException(ContactsListAdapter.java:37)

这是我的自定义列表适配器类:

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;
}

}

这是我的 ListView 活动:

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();
}

}

有任何想法吗?

4

1 回答 1

1

(我的基本假设没有看到你的 logcat 错误)

因为你忘记了

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

就像是,

View v = convertView;

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

您正在膨胀视图但未将其分配给View v. 这就是为什么你要NullPointerException使用nameTextViews email

于 2013-01-17T19:40:11.173 回答