自定义列表适配器中的空指针异常

时间:2013-01-17 19:37:10

标签: android android-listview android-arrayadapter

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

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

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

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

}

有什么想法吗?

1 个答案:

答案 0 :(得分: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。这就是您在NullPointerExceptionname TextView上获得email的原因。