将联系人照片加载到联系人列表中:随机联系人照片出现在错误的位

时间:2011-11-01 13:34:16

标签: java android simplecursoradapter contactscontract

我已使用扩展的SimpleCursorAdapter将我的联系人加载到列表中,现在我正在尝试加载联系人照片。运行代码时随机联系人照片会出现在随机联系人旁边,即使对于那些没有照片的人也是如此。为什么不为那些拥有它们并在旁边显示的联系人获取照片呢?

以下是代码:

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);
    }

以及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;
}

1 个答案:

答案 0 :(得分:0)

在bindView()中,您正在调用:

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

你不应该在view参数上调用findViewById()吗?

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