Racker Racker - 6 months ago 33
Android Question

Android: Set contact photo in a ListView with name and number

I'm creating an app that needs to display the phone contacts with its photo, name and number. I've created a ListView and can show contacts and numbers with a generic photo, but I can't show contat's picture. This is my code:



Cursor cursor = getContacts();

String[] fields = new String[] {Contacts.DISPLAY_NAME, Phone.NUMBER};

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor,
fields, new int[] {R.id.contactEntryText, R.id.contactEntryNumber});

mContactList.setAdapter(adapter);

private Cursor getContacts()

// Run query
Uri uri = Phone.CONTENT_URI;
String[] projection = new String[] {
Contacts._ID,
Contacts.DISPLAY_NAME,
Phone.NUMBER,
Contacts.PHOTO_ID

};
//String selection = Contacts.HAS_PHONE_NUMBER + "='1'";
String selection = null;
String[] selectionArgs = null;
String sortOrder = Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}




How can I attach the contact's picture in the SimpleCursorAdapter? Is there another?

Thank you very much.

Answer

I figured it out. If someone had the same problem, this is how i did it:

In an activity that extends ListActivity:

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Cursor names = getNamesAndPictures();
    names.moveToFirst();        
    ListAdapter adapter = new MySimpleCursorAdapter(this, R.layout.contacts,
                names, new String[] {Phones.NAME, Phones.NUMBER}, new int[] {
                R.id.Nombre, R.id.Numero});
    setListAdapter(adapter);
    startManagingCursor(names);
    Log.i(DEBUG_TAG, "Mi numero: " + miNumeroTelefono());        
}

public Cursor getNamesAndPictures(){
     String[] projection = new String[] {
             Phones.NUMBER,
             Phones.PERSON_ID,
             People.NAME,
             People._ID
     };
     String selection = Phones.NAME + "!='null'";
     String sortOrder = Phones.NAME + " COLLATE LOCALIZED ASC";
     Cursor cursor = managedQuery(Phones.CONTENT_URI, projection, selection, null, sortOrder);
     return cursor;
}

In a custom adapter:

public class MySimpleCursorAdapter extends SimpleCursorAdapter {

  ...

  @Override
  public void bindView(View view, Context context, Cursor cursor) {
      ImageView imageView = (ImageView) view.findViewById(R.id.Foto);

      int id = cursor.getColumnIndex(Phones.PERSON_ID);
      Uri uri = ContentUris.withAppendedId(Phones.CONTENT_URI, cursor.getLong(id));
      String uriPhoto = uri.toString();
      String uriPeople = uriPhoto.replace("phones", "people");

      Uri uriFinal = Uri.parse(uriPeople);

      Bitmap bitmap = People.loadContactPhoto(context, uriFinal, R.drawable.avatar02, null);
      imageView.setImageBitmap(bitmap);
      super.bindView(view, context, cursor);
  }
}