I am trying to set a birthday to the android contacts provider to an existent contact which doesn't have the field, I have tried to use the method I use to update the birthday of a contact which already has a birthday set:
fun updateBirthdate(id: Long, birthdate: String) {
val list = ArrayList<ContentProviderOperation>()
val where = """${ContactsContract.Data.CONTACT_ID} = ?
AND ${ContactsContract.Data.MIMETYPE} = ?"""
val whereParams =
arrayOf(id.toString(), ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)
list.add(ContentProviderOperation.newUpdate(
ContactsContract.Data.CONTENT_URI)
.withSelection(where, whereParams)
.withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthdate)
.withValue(ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
.build())
context.contentResolver.applyBatch(ContactsContract.AUTHORITY, list)
}
But it's not working, I also tried to insert a new row:
list.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.Event.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.Event.START_DATE, birthdate)
.withValue(CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
.build())
But none of the above works, any help?
first, your method
updateBirthdatehas a bug, if you have a contact that has multiple events set for it, e.g birthday, anniversary, etc. your code will override all of them.you should instead query to find the specific raw contact in which that event is saved, and update only that specific raw contact (add Data.RAW_CONTACT_ID = ? to your selection).
when updating an existing contact that doesn't currently have a birthday you're right to change the
updateto aninserthowever thewithValueBackReferenceline will only work if you're currently creating a new raw contact, which I assume you do not. so change that to a regularwithValueand add to ID of the raw contact you're trying to add the birthday to