2

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;
}
RufusInZen
  • 2,119
  • 1
  • 19
  • 26

1 Answers1

0

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);
Sofi Software LLC
  • 3,879
  • 1
  • 36
  • 34
  • yes, thank you! This partially solved the problem - it now shows the correct photos next to correct contacts. But I still get random photos next to random other contacts who don't have contact photos. Any ideas? – RufusInZen Nov 02 '11 at 13:23
  • To clarify, this happens when I start scrolling the list. Could it be because of getView or newView, should I be overwriting those too or something? – RufusInZen Nov 02 '11 at 13:29
  • Found the other culprit as well - my bindView was recycling the rows so I had previously loaded photos appear in random other rows. Fixed by adding an `else` statement to `if (photoBitmap != null)`. Thanks for the help! – RufusInZen Nov 04 '11 at 10:51