Android没有找到联系人照片

时间:2014-08-29 14:18:16

标签: android photo contact

我需要你的帮助来获取我的联系人照片。

我在生日那天收到了所有联系人。现在我必须尝试这样的人的照片:

 ...
 while (contactCursor.moveToNext()) {
  Contact c = Contact.createContact(contactCursor);
  c.setPhoto(getContactPhoto(contentResolver, c.getId()));
  contacts.add(c);
 }
 ..

private static InputStream getContactPhoto(ContentResolver contentResolver, long contactId) {
        Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
        Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
        Cursor cursor = contentResolver.query(photoUri, new String[] {ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
        if (cursor == null) {
            return null;
        }
        try {
            if (cursor.moveToFirst()) {
                byte[] data = cursor.getBlob(0);
                if (data != null) {
                    return new ByteArrayInputStream(data);
                }
            }
        } finally {
            cursor.close();
        }
        return null;
    }

我现在的问题是我无法收到任何联系人的照片(cursos size = 0)。在手机上(Xperia Z1 Compact)绝对是联系人照片。

我的目标是将照片设置为:

    if(contact.getPhoto() != null) {
        Bitmap cPhoto = BitmapFactory.decodeStream(contact.getPhoto());
        holder.photo.setImageBitmap(cPhoto);
    } else {
        ShapeDrawable d = new ShapeDrawable(new OvalShape());
        d.getPaint().setColor(Color.BLUE);
        d.setBounds(10, 10, 20, 20);
        holder.photo.setImageDrawable(d);
    }

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

试试这个

 public void getContacts(ContentResolver cr) {
    Cursor cursor = cr.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
            null, null);
    while (cursor.moveToNext()) {
        String name = cursor
                .getString(cursor
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

        String photoUri = cursor
                .getString(cursor
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));

        friendsListitem = new FriendsListitem(name, photoUri, phoneNumber);
        arrayListFriends.add(friendsListitem);
    }
    cursor.close();// close cursor
 }

使用Picasso加载图片

Picasso.with(getApplicationContext())
                .load(Uri.parse(photoUri)).noFade()
                .into(imageView);