我一整天都在尝试为Android联系人添加照片联系人。最后我将图片添加到联系人,但我无法添加任何姓名或电话号码。联系人显示为"(未知)",带有正确的照片。
我的代码:
private void addContact2() {
final String displayName = "XYZA";
final String mobileNumber = "666666";
final byte[] photoByteArray; // initalized elsewhere
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "")
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "")
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName)
//.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, displayName)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photoByteArray)
.build());
Uri newContactUri = null;
ContentProviderResult[] res = null;
try {
final ContentResolver contentResolver = getContentResolver();
res = contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
if (res != null && res.length > 0 && res[0] != null) {
newContactUri = res[0].uri;
Log.d(CallActivity.class.getName(), "URI added contact:"+ newContactUri);
Toast.makeText(this, "Successfully added " + displayName, Toast.LENGTH_LONG).show();
}
else Log.e(CallActivity.class.getName(), "Contact not added.");
} catch (NullPointerException | RemoteException | OperationApplicationException e) {
Log.e(CallActivity.class.getName(), e.getMessage(), e);
}
}
答案 0 :(得分:1)
好的,我已修好了。在“name”ops.add上,我写了.withValue(ContactsContract.Data.RAW_CONTACT_ID, 0)
而不是.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
。现在一切正常。