How to only update contacts instead adding in sync adapter

768 views Asked by At

I have few numbers stored in my apps database. I wanted to match those numbers in contacts app and update that contact with mimetype. Basically how Whatsapp does. They sync all contacts and their app icon comes in contact.

I have done sync part and if i add new contact then i am able to show my app icon in the contact . But my requirement is to just update the existing contact.

This is what i have tried to update the contact,

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        ops.add(ContentProviderOperation.newInsert(addCallerIsSyncAdapterParameter(Data.CONTENT_URI, true))
            .withValueBackReference(Data.RAW_CONTACT_ID,id)
            .withValue(Data.MIMETYPE, MIMETYPE)
            .withValue(Data.DATA1, "Username")
            .withValue(Data.DATA2, "Ite's Me")
            .build());

        try {
            context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

and rawContactid i am fetching from

Cursor cursor = context.getContentResolver().query(Data.CONTENT_URI, new String[] {Data.RAW_CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.CONTACT_ID }, 
             ContactsContract.CommonDataKinds.Phone.NUMBER + "= ?", 
                     new String[] {phonenumb}, null);

I am not able to add connections into that contact. What am i doing wrong. Can somebody please help me with this.

Thanks in advance.

2

There are 2 answers

0
Febri Arianto On

insert your person data to new raw_contact, then merge it to existing raw_contact._id in your cotacts list using agregationexception.

ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
        ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(ContactsContract.AggregationExceptions.CONTENT_URI);
        builder.withValue(ContactsContract.AggregationExceptions.TYPE, ContactsContract.AggregationExceptions.TYPE_KEEP_TOGETHER);
        builder.withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID1, raw1);
        builder.withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID2, raw2);
        ops.add(builder.build());
0
Patrick Brennan On

The problem is that you're using withValueBackReference to reference the raw contact id. This will try to get the id of the raw contact using your parameter as an index to a previous operation in the batch, i.e. if id=0, it will refer back to the first operation, and if it was an insert of a new raw contact, use the generated id as the raw contact id for the insert of the contact data. You want to use withValue here, since you already have the raw contact id.