ContentResolver 常用来操作内置数据库.
在用此类插入数据库的时候, 尝尝使用的是 insert.
但是这个操作速度极慢.(因为此函数是能确保插入结果,所以每一次操作都是一个事物)
有两种办法提高插入效率:
1> 使用 ".bulkInsert()" 可以一次插入多个.
2> ".applyBatch();" 也可以一次插入多个.
下面是applyBatch 示范代码: (bulkInsert就不用示范吧?)
ArrayList<ContentProviderOperation> ops =new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null)
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE) // "vnd.android.cursor.item/name"
.withValue(StructuredName.FAMILY_NAME, "aaaaaaaa")
.build());StructuredName.
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "1111111111111")
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM)
.withValue(ContactsContract.CommonDataKinds.Phone.LABEL, "x手机号x")
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "222222222")
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM)
.withValue(ContactsContract.CommonDataKinds.Phone.LABEL, "o手机号o")
.build());
// ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
// .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
// .withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
// .withValue(Email.DATA, "xxx@xx.x")
// .withValue(Email.TYPE, Email.TYPE_WORK)
// .build());
ContentProviderResult[] results;
try {
results = mContext.getContentResolver()
.applyBatch(ContactsContract.AUTHORITY, ops);
for(ContentProviderResult result : results) {
Log.i("XXXX", result.uri.toString());
}
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}