views:

146

answers:

2

Hi stackies,

I'm having Facebook for Android on my phone which automatically synces the FB profile pictures of the people in my contact list to my phone.

I'd like to use those pictures within my app where I access ContactsContract.PhoneLookup.

Do I really need the Facebook SDK to do that? I guess not, but I cannot find any evidence of the pictures being saved somewhere around ContactsContract...

Thanks in advance!
S.

+1  A: 

You simply need to query for the Photo URI and use the URI as per your needs.

This method will help you

/**
 * @return the photo URI
 */
public Uri getPhotoUri() {
    try {
        Cursor cur = this.ctx.getContentResolver().query(
                ContactsContract.Data.CONTENT_URI,
                null,
                ContactsContract.Data.CONTACT_ID + "=" + this.getId() + " AND "
                        + ContactsContract.Data.MIMETYPE + "='"
                        + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
                null);
        if (cur != null) {
            if (!cur.moveToFirst()) {
                return null; // no photo
            }
        } else {
            return null; // error in cursor process
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long
            .parseLong(getId()));
    return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}

Or there is another approach:

public Uri getPhotoUri(Integer contactid) {
    Cursor photoCur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'", null, ContactsContract.Contacts.DISPLAY_NAME+" COLLATE LOCALIZED ASC");
    photoCur.moveToPosition(contactid);
    Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, photoCur.getLong(photoCur.getColumnIndex(ContactsContract.Contacts._ID)));
    Uri photo = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
    return photo;
}

Please note that the URI record may not exists. If the images for example are stored on the SDCard and that is not present, the URI will return no photo about it. For this you need to do further checks.

This will help you also (if Uri fails it sets a default placeholder image):

and calling that function (contactimage is an ImageView):

Uri contactphoto = objContact.getPhotoUri();
contactimage.setImageURI(contactphoto);
try {
    String nullString = contactimage.getDrawable().toString();
} catch (java.lang.NullPointerException ex) {
    contactimage.setImageResource(R.drawable.contactplaceholder);
}
Pentium10
Wow, that was fast! Thanks so much!
Sotapanna
My app looks MUCH better now! YAY! :)
Sotapanna
A: 

When I use this method I get a nullpointerexception on the imageview. What am I doing wrong?

Yash