我想将图像添加到联系人,但我无法将图像添加到联系人,但如果联系人图像存在,它将替换现有图像并进行设置。但是,当我们要换新的时,它却无法工作......请帮助任何人...提前致谢
try {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 75, stream);
android.content.ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI);
builder.withSelection(
ContactsContract.Data.CONTACT_ID + "=?" + " AND "
+ ContactsContract.Data.MIMETYPE + "=?",
new String[] {
String.valueOf(contactId),
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE });
builder.withValue(
ContactsContract.CommonDataKinds.Photo.PHOTO,
stream.toByteArray());
ops.add(builder.build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY,
ops);
} catch (Exception e) {
e.printStackTrace();
}
案例R.id.assign_contact:
cropstatus = 2;
filepath = Environment.getExternalStorageDirectory().getPath()
+ "/Noredoo/Profile Pictures/" + file.getName();
startCropImage(filepath, 1, 1);
Intent contactintent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(
Intent.createChooser(contactintent, "Choose Contact"),
PICK_CONTACT);
return true;
答案 0 :(得分:1)
您遇到的问题是,在插入新图像时,您需要使用此处所述的其他方法。
如果联系人还没有图片,则无法更新该字段,因为它不存在。您应该执行插入操作。
以下是实现该目标的工作代码示例:
// Creating new photo entry
int rawContactId = -1;
Cursor cursor = resolver.query(ContactsContract.RawContacts.CONTENT_URI, null, ContactsContract.RawContacts.CONTACT_ID + "=?", new String[] {id}, null);
if(cursor.moveToFirst()) {
rawContactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.RawContacts._ID));
if(rawContactId > -1) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID, rawContactId)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photoBytes)
.build());
try {
resolver.applyBatch(ContactsContract.AUTHORITY, ops);
}
catch (Exception e) {
e.printStackTrace();
}