Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

android - Edit name/phone number of contact programmatically

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", "" + 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...