Ollie C
Ollie C

Reputation: 28519

Extract a contact's photo

Gah, another scenario here something that should be simple is proving to be very time-consuming and painful.

I'm using this to query the contacts provider:

private Cursor getContacts(){
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
    ContactsContract.Contacts._ID,
    ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.Contacts.PHOTO_ID
    };
    ......
    return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}

This works fine and retrieves contact names, and on a handful of contacts it shows a numeric ID for the PHOTO_ID field, which I assume is the PHOTO_ID I'm requesting. But then I push that ID into this method to extract the bitmap, it fails on every contact and the stream is null every time. I'm testing against a set of contacts that includes some with Android contact photos (I know there are some issues extracting photos from Facebook contacts).

private Bitmap loadContactPhoto(long id) {
    Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
    InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri);
    if (input == null) return null;
    Bitmap bitmap = BitmapFactory.decodeStream(input);
    return bitmap;
}

What have I missed?

Upvotes: 3

Views: 4951

Answers (1)

mikerowehl
mikerowehl

Reputation: 2238

openContactPhotoInputStream() takes the uri of the contact, try calling it with the ContactsContract.Contacts._ID column instead of the PHOTO_ID column and you should see better results.

There's a bunch of relevant discussion here with some code to check out:

How do I load a contact Photo?

Note that in some cases you'll see a photo in the native contacts app which won't load through the content resolver. Some sync info, like Facebook for example, is flagged to be used only by the contacts app itself and doesn't get exported to other apps :-(

However, using the contactUri should take care of at least some of your issues.

Upvotes: 2

Related Questions