What is missing from your code is the mapping from the Contact
objects to the views inside the ListView
. The most basic solution I can think of right now would look something like this:
public class ContactAdapter extends BaseAdapter {
private final List<Contact> contactList;
private final LayoutInflater layoutInflater;
public ContactAdapter(Context context, List<Contact> contactList) {
this.layoutInflater = LayoutInflater.from(context);
this.contactList = contactList;
}
@Override
public int getCount() {
return this.contactList.size();
}
@Override
public Contact getItem(int position) {
return this.contactList.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// You get the Contact object for the current position
Contact contact = getItem(position);
// If the convertView is null we need to create a new one.
if(convertView == null) {
convertView = this.layoutInflater.inflate(R.layout.list_item, parent, false);
// We pass the view to our ViewHolder and set the ViewHolder as tag to the View
ContactViewHolder holder = new ContactViewHolder(convertView);
convertView.setTag(holder);
}
// We get the ViewHolder from the tag and bind the Contact object to it.
ContactViewHolder holder = (ContactViewHolder) convertView.getTag();
holder.bind(contact);
return convertView;
}
private class ContactViewHolder {
private final TextView tvName;
private final TextView tvTelephone;
public ContactViewHolder(View convertView) {
// We get the TextViews from the convertView
this.tvName = (TextView) convertView.findViewById(R.id.tvName);
this.tvTelephone = (TextView) convertView.findViewById(R.id.tvTelephone);
}
public void bind(Contact contact) {
// We set the values of our TextViews according to the Contact object.
this.tvName.setText(contact.getName());
this.tvTelephone.setText(contact.getTelephoneNumber());
}
}
}
This is a simple adapter which uses the ViewHolder pattern for increased scroll performance. It should all be very self explanatory, nevertheless if you have questions feel free to ask. Here is the layout R.layout.list_item
which I used for testing, it just contains the two TextViews
tvName
and tvTelephone
in a RelativeLayout
:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tvTelephone"
android:layout_below="@id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>