创建一个应用程序,我在其中使用内容提供程序在recyclerview中获取所有设备联系人。我的所有联系人和联系人姓名即将开始,但联系人图片未显示。
我的图片为空,但图片是在我的设备联系人上设置的。 这就是我所做的。
private void getAllContacts() {
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String image_uri = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_URI));
contactVO = new Contact();
contactVO.setContactImage(image_uri);
contactVO.setContactName(name);
/*if (image_uri != null) {
image.setImageURI(Uri.parse(image_uri));
}*/
phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id},
null);
if (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactVO.setContactNumber(phoneNumber);
if (Objects.equals(phoneNumber, mobile)) {
contactArrayList.add(contact);
}
}
phoneCursor.close();
//object of model class
contactArrayList.add(contactVO);
}
}
答案 0 :(得分:0)
如果您有contactID
,则可以通过将联系人ID添加到联系人Contacts.Photo.CONTENT_DIRECTORY
轻松获取联系人图片
private Uri retrieveContactPhoto(String id) {
return Uri.withAppendedPath(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(id)),
ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
然后使用Glide
的{{1}}将联系人图片加载到imageview
Picasso
答案 1 :(得分:0)
你可以试试这个: 联系人由getId()标识:
/**
* @return the photo URI
*/
public Uri getPhotoUri() {
try {
Cursor cur = this.ctx.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID + "=" + this.getId() + " AND "
+ ContactsContract.Data.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
null);
if (cur != null) {
if (!cur.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long
.parseLong(getId()));
return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
用法是:
Uri u = objItem.getPhotoUri();
if (u != null) {
mPhotoView.setImageURI(u);
} else {
mPhotoView.setImageResource(R.drawable.ic_contact_picture_2);
}
希望这会对你有所帮助。