Search code examples
javaandroidsimplecursoradaptercontactscontract

Loading contact photos into contact list: random contact photos appear in wrong places


I have loaded my contacts into a list using extended SimpleCursorAdapter and now I'm trying to load the contact photos. When running the code random contact photos appear next to random contacts, even for those who don't have photos. Why doesn't it just get the photos for those contacts who have them and show next to them?

Here is the code:

public void bindView(View view, Context context, Cursor cursor) {
ImageView photo = (ImageView) findViewById(R.id.photo);
long photoId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));

Bitmap photoBitmap = loadContactPhoto(photoId);
    if (photoBitmap != null) {
        photo.setImageBitmap(photoBitmap);
    }

And the code to loadContactPhoto:

public Bitmap loadContactPhoto(long id) {
    Uri contactUri = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, id);
    byte[] data = null;
    Cursor cursor = managedQuery(
        contactUri, // Uri
        new String[] { ContactsContract.CommonDataKinds.Photo.PHOTO }, // projection, the contact photo
        ContactsContract.Contacts.PHOTO_ID + "!= 0", // where statement, only if the contact has a photo
        null, null);
    Log.i(LOG_TAG, "cursorCount: " + cursor.getCount()); // returns 1
    if (cursor == null || !cursor.moveToNext()) {           
        return null;
    }
    data = cursor.getBlob(0);
    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
    return bitmap;
}

Solution

  • In bindView(), you're calling:

    ImageView photo = (ImageView) findViewById(R.id.photo);
    

    Shouldn't you be calling findViewById() on the view parameter?

    ImageView photo = (ImageView) view.findViewById(R.id.photo);