Search code examples
androidcontactscontract

Adding contacts using ContactsContract in batch


Can anyone please help me on adding new contacts in address book and apply them in batch by using new ContactsContract API? I could not find a proper tutorial on this.

I am able to add a single contact. But batch update fails with Unknown contacts being added.

Currently I am looping through while loop while collecting info. of users to write, store it in the ArrayList<ContentProviderOperation> and applying and

ContentProviderResult[] result = getContentResolver().applyBatch(ContactsContract.AUTHORITY, op_list);

But only one contact is updated with name and other are updated as unknown contacts.

Please help with a sample code which adds the fields like name,nickname,mobile,title,email,Skype id,work-country etc.

Any help ? Thanks .


Solution

  • This is my code that worked, you can add the fields as you require for other values:

    int backRefIndex = 0
    
    ArrayList<ContentProviderOperation> op_list = new ArrayList<ContentProviderOperation>();
                            
    op_list.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI).withValue(RawContacts.ACCOUNT_TYPE, null).withValue(RawContacts.ACCOUNT_NAME, null) 
                                .build());      
    op_list.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRefIndex).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "Contact_name").build());
    
    op_list.add(ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID,backRefIndex).withValue(Phone.MIMETYPE,Phone.CONTENT_ITEM_TYPE).withValue(Phone.NUMBER,"1234567890").withValue(Phone.TYPE,Phone.TYPE_MOBILE).withValue(Phone.TYPE, Phone.TYPE_WORK).build());
    
    try {
        ContentProviderResult[] result = context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, op_list);
    } catch (OperationApplicationException exp) {
        exp.printStackTrace();
    } catch (RemoteException exp) {
        exp.printStackTrace();
    }