Android中在进行批量操作数据库时,有一个方法很难理解,经过长时间琢磨,将心得分享如下:
int backRef = ops.size();
Log.d(TAG, "backRef: " + backRef);
ContentValues values = new ContentValues();
ops.add(ContentProviderOperation
.newInsert(RawContacts.CONTENT_URI)
// .withValues(values).build());
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, backRef)
.withValues(getPeopleCV()).build());
if (nickName != null) {
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, backRef)
.withValue(Data.MIMETYPE, Nickname.CONTENT_ITEM_TYPE)
.withValue(Nickname.NAME, getDecodeValue(nickName)).build());
}
if (birthday != null) {
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, backRef)
.withValue(Data.MIMETYPE, Event.CONTENT_ITEM_TYPE)
.withValue(Event.TYPE, Event.TYPE_BIRTHDAY)
.withValue("data1", getDecodeValue(birthday)).build());
}
withValueBackReference(Data.RAW_CONTACT_ID, backRef)
backRef指的是:第backRef条批处理数据执行完成后,生成的索引值,将作为当前这条记录的Data.RAW_CONTACT_ID字段的值。从而解决了批量插入联系人信息时无法拿到rawContactId的问题。