shvivek
shvivek

Reputation: 328

Android: unable to update my contacts through programming

I have written the code for simple update.I am able to insert and delete the data from the the contacts of my AVD but when I want to update the data,its not updating.

here is my sample code:

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            String rawContactInsertIndex = (Integer.toString(ops.size()));

ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                        .withSelection( Data.CONTACT_ID + "=?" , new String[] { rawContactInsertIndex })                        
                    .withValue(StructuredName.DISPLAY_NAME, firstname)
                    .withValue(StructuredName.FAMILY_NAME, lastname) 
                    .withValue(StructuredName.GIVEN_NAME, firstname)

can any one help? I am stuck here.

Upvotes: 0

Views: 388

Answers (1)

Jens
Jens

Reputation: 17077

To start, your .withSelection(Data.CONTACT_ID + "=?", new String[]{rawContactInsertIndex} is going to perform an update on all data columns where the Data.CONTACT_ID column has the value 0. This includes phone numbers, addresses etc. etc.

Fortunately, there's no such contact apparently, because you'd f-ck that contact up royally.

To start, you should fetch the correct CONTACT_ID and do some work on your selection, i.e. do a selection on the Data.MIME_TYPE also.

contactId = Fetch the correct row identifier of the contact you want to update.

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
    .withSelection(Data.CONTACT_ID + "=? AND " + Data.MIME_TYPE + "=?",
        new String[]{contactId, StructuredName.CONTENT_ITEM_TYPE})
    .withValue(StructuredName.DISPLAY_NAME, firstName)
    .withValue(StructuredName.FAMILY_NAME, lastName)
    .withValue(StructuredName.GIVEN_NAME, givenName).build());

Also, are you sure you should be updating on CONTACT_ID? Consider using RAW_CONTACT_ID.

Upvotes: 1

Related Questions