3

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.

Henrique
  • 4,921
  • 6
  • 36
  • 61
  • Older versions of Android (https://android.googlesource.com/platform/frameworks/base/+/gingerbread/core/java/android/provider/ContactsContract.java#1160) didn't support lookup URIs, but Google doesn't mention this in the docs of course :-( – Daniele Ricci Apr 07 '16 at 11:44

1 Answers1

7

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;
}
Henrique
  • 4,921
  • 6
  • 36
  • 61
  • +1, How much time (as in milliseconds) does it take to retrieve one photo?, What `uri` you are passing into this method? – Gaurav Agarwal Sep 04 '12 at 19:17
  • Not sure there's an exact number of milliseconds for the photo retrieval, I'm guessing it depende on the phone's processor. As for the other question, this is the URI that I'm sending: Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, contactId); – Henrique Sep 04 '12 at 21:53
  • +1 on answer, you are right it depends on processor speed. Thanks. – Gaurav Agarwal Sep 05 '12 at 01:51