如何在android上更新多组联系人?



刚刚成功插入多个分组到联系人,但是在联系人上更新多个分组失败. 我的代码只更新了一个组,而不是所有的groupsId列表(见下文)

private fun updateGroupOnContact(
operations: ArrayList<ContentProviderOperation>,
where: String,
args: Array<String>,
groupsId: Array<String>
) {
val values = ContentValues()
groupsId.forEach {
val newVal = ContentValues()
newVal.put(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID, it)
values.putAll(newVal)
}
operations.add(
ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, args)
.withValues(values)
.build()
)
}

我已经尝试了这个代码:

groupsId.forEach {
operations.add(
ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, args)
.withValue(
ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID, it
)
.build()
)
}

成功的代码创建新联系人与多组。

contentProvideOperation.add(
ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(
ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID,
groupID
)
.withValue(
ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE,
ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE
)
.build()
)

任何帮助都是感激的。

实际上我得到了错误的id联系人插入它,我应该使用原始联系人id与这个函数。

private fun getRawContactId(contactId: String): String? {
val projection = arrayOf(RawContacts._ID)
val selection = RawContacts.CONTACT_ID + "=?"
val selectionArgs = arrayOf(contactId)
val c: Cursor = contentResolver?.query(
RawContacts.CONTENT_URI,
projection,
selection,
selectionArgs,
null
)
?: return null
var rawContactId = -1
if (c.moveToFirst()) {
rawContactId = c.getInt(c.getColumnIndex(RawContacts._ID))
}
c.close()
return rawContactId.toString()
}

然后插入它(用于添加联系人的组),而不是使用update。因为update只设置组只有1个组

private fun insertGroupOnContact(
operations: ArrayList<ContentProviderOperation>,
contactId: String,
groupId: String
) {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValue(Data.RAW_CONTACT_ID, getRawContactId(contactId))
withValue(GroupMembership.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE)
withValue(GroupMembership.GROUP_ROW_ID, groupId)
operations.add(build())
}
}

清除前一个联系人的群组并插入多个群组。它应该首先更新它(1组)以删除先前的,然后插入其他组。

private fun updateGroupOnContact(
operations: ArrayList<ContentProviderOperation>,
where: String,
args: Array<String>,
groupId: String
) {
operations.add(
ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(where, args)
.withValue(GroupMembership.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE)
.withValue(GroupMembership.GROUP_ROW_ID, groupId)
.build()
)
}

最新更新