以编程方式编辑联系人姓名

时间:2018-07-31 21:01:51

标签: java android

我正在修改联系人的姓名和电话号码。我修改了联系电话,所以

  ContentResolver cr = getContentResolver();

    String where = ContactsContract.Data.CONTACT_ID + " = ? AND " +
            ContactsContract.Data.MIMETYPE + " = ? AND " +
            String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";
    String[] params = new String[] {idContact,
            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
            String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)};

    Cursor phoneCur = managedQuery(ContactsContract.Data.CONTENT_URI, null, where, params, null);

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

    if ( (null == phoneCur)  ) {
        //createContact(name, phone);
        Log.d("click","Done crate");

    } else {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(where, params)
                .withValue(ContactsContract.CommonDataKinds.Phone.DATA, phone)
                .build());
    }

    phoneCur.close();

    try {
        cr.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (OperationApplicationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

但我不知道如何更改联系人的姓名。

如何编辑名称?

1 个答案:

答案 0 :(得分:0)

确定!这段代码。

ContentResolver cr = getContentResolver();

    String where = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " +
            ContactsContract.Data.MIMETYPE + " = ? ";
    String[] params = new String[] {idContact,
            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};

    Cursor phoneCur = managedQuery(ContactsContract.Data.CONTENT_URI, null, where, params, null);

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

    if ( (null == phoneCur)  ) {
        //createContact(name, phone);

    } else {

        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(where, params)
                //.withValue(ContactsContract.CommonDataKinds.Phone.DATA, phone)
                .withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, etName.getText().toString())
                .build());

    }

    phoneCur.close();

    try {
        cr.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (OperationApplicationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}