Question

I'm modifying my app to store information on contacts using LOOKUP_KEY instead of _ID as suggested by the API docs. The only problem I'm having is that I'm no longer able to load the contact's photo.

The problematic code is this one:

InputStream s = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(), contactUri);

This is returning the following error: java.lang.IllegalArgumentException: URI: content://com.android.contacts/contacts/lookup/1424i118.2312i1220228108/photo

The contactUri that I am using as argument is acquired by the following: Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, contact_key);

and in this example, contact_key is 1424i118.2312i1220228108

Based on the API docs, this helper method should work with both CONTENT_URI or CONTENT_LOOKUP_URI, which I am using.

Any ideas? Thanks.

Was it helpful?

Solution

For anyone with a similar problem, this did the trick for me:

public Bitmap getPhoto(Uri uri){
    Bitmap photoBitmap = null;

    String[] projection = new String[] { ContactsContract.Contacts.PHOTO_ID };

    Cursor cc = getContentResolver().query(uri, projection, null, null, null);

    if(cc.moveToFirst()) {
        final String photoId = cc.getString(cc.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
        if(photoId != null) {
            final Cursor photo = managedQuery(
                    Data.CONTENT_URI,
                    new String[] {Photo.PHOTO},
                    Data._ID + "=?",
                    new String[] {photoId},
                    null
            );

            // Convert photo blob to a bitmap
            if(photo.moveToFirst()) {
                byte[] photoBlob = photo.getBlob(photo.getColumnIndex(Photo.PHOTO));
                photoBitmap = BitmapFactory.decodeByteArray(photoBlob, 0, photoBlob.length);
            }

            photo.close();
        }

    } 
    cc.close();

    return photoBitmap;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top