简体   繁体   中英

Android contact data fields can edit but not create

I use this code to update a contact's address, but it only works for contacts that have an existing address. If the contact address field is empty, the update() method returns zero and the contact data is not updated. How do I add an address to an existing contact?

//str_id is the contact's ID
//input is the String representing an address
ContentValues cv = new ContentValues();
String[] params = new String[] { str_id, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
cv.put(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, input);
getContentResolver().update(ContactsContract.Data.CONTENT_URI, cv, ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?", params);

I have also tried the equivalent logic with a ContentProviderOperation, but get the same result. Just like my previous example, I can update an existing address but cannot create an address.

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, id)
    .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, input)
    .build());

You need to check whether Adress exist or not before updating Address, If address exist your above code will work fine as you are doing just update..

While doing insert address, actually you are doing a child insert" see here , Very good explanation of ContentProviderOperation which relates to your issue closely..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM