Android 批量插入聯絡人 分享
大體的問題是這樣的:
class VCardEntry{String name;
String[] number;
getDisplayName();
getPhoneList()
class phone {
getNumber();
}
}
傳來的資料:
這些是從網路端截獲的資料
name :zhangsan
number : 123,456,789 (好幾個號碼)
name:lisi
number :111,222,333
name:wangwu
number:159753
。。。。。。
等好幾百個數據
ArrayList<VCardEntry> list;
需要批量存入資料庫
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ArrayList<VCardEntry> list = params[0];
Iterator<VCardEntry> it = null;
if (list != null) {
it = list.iterator();
}
Logger.v(TAG,"--->doInBackground it:"+it);
int rawContactInsertIndex = 0;
while(it!= null && it.hasNext()) {
VCardEntry mv = it.next();
rawContactInsertIndex = ops.size(); // 有了它才能給真正的實現批量新增
Logger.v(TAG,"--->>>>>>>name:"+mv.getDisplayName());
Logger.v(TAG,"--->>>>>>>getPhoneList:"+mv.getPhoneList());
if (mv.getPhoneList() != null) {
ops.add(ContentProviderOperation
.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, ACCOUNT_NAME)
.withValue(RawContacts.ACCOUNT_NAME, ACCOUNT_TYPE)
.withYieldAllowed(true).build());
// add name
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, mv.getDisplayName())
.withYieldAllowed(true).build());
// add number
for(VCardEntry.PhoneData phone : mv.getPhoneList()) {
Logger.v(TAG,"--->>>>>>>number:"+phone.getNumber());
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, phone.getNumber())
.withValue(Phone.TYPE, Phone.TYPE_MOBILE)
.withValue(Phone.LABEL, "")
.withYieldAllowed(true).build());
}
}
}
ContentProviderResult[] results = null;
if (ops != null) {
try {
results = mContext.getContentResolver()
.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
Logger.e(TAG,String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
Logger.e(TAG,String.format("%s: %s", e.toString(), e.getMessage()));
}
}