我已经使用扩展的 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);
}
以及加载ContactPhoto 的代码:
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;
}