2013-01-17 50 views
0

嘗試使用自定義數組適配器顯示聯繫人列表。但是我每次運行我的應用程序時,我得到以下錯誤:自定義列表適配器中的空指針異常

顯示java.lang.NullPointerException在com.example.contactsapp.ContactsListAdapter.getView(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", "[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(); 
} 

}

任何想法?

+1

你能指出什麼是第37行嗎? – petey

回答

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。這就是爲什麼你NullPointerExceptionnameemail TextViews。

+0

謝謝!解決了這個問題。 – Javacadabra

相關問題