Edit name/phone number of contact programmatically

旧时模样 提交于 2019-11-28 03:21:54

问题


I am trying to modify displayed name of a contact programmatically:

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

        ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
        .withSelection(ContactsContract.CommonDataKinds.Phone._ID + " = ?", new String[] {contact_id})
        .withValue(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, "anything")
        .build());

        ContentProviderResult[] result = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (Exception e) {
        Log.w("UpdateContact", e.getMessage()+"");
        for(StackTraceElement ste : e.getStackTrace()) {
            Log.w("UpdateContact", "\t" + ste.toString());
        }
        Context ctx = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(ctx, "Update failed", duration);
        toast.show();
    }

contact_id is ContactsContract.CommonDataKinds.Phone._ID gathered in previous activity

Code executes fine, but:

  • ContentProviderResult[] result is null
  • Contact name remains unchanged

I've experimented also with Data.DISPLAY_NAME but with same effect.

I read the Manual: http://developer.android.com/guide/topics/providers/contacts-provider.html but I don't want to call native intent.

Thanks.


回答1:


You should specify the mimetype in your selection.

.withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
               Data.MIMETYPE + "='" +
               ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
               new String[]{contact_id})

If you haven't figured this out yet, give that a go. I found updating contacts to be very tricky in getting the selection arguments right.



来源:https://stackoverflow.com/questions/16887240/edit-name-phone-number-of-contact-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!