更新android中联系人的信息

时间:2013-08-02 04:47:32

标签: android

我想更新联系人的新信息。我需要更新3个字段:联系人的姓名,电话号码和公司名称。这是我的代码。我的问题是:方法不会更新任何新信息

你能告诉我出错的原因吗?并告诉我如何解决它!谢谢你们!

public void editContact(String _id, String name, String phone, String company) {
    ContentResolver cr = getContentResolver();

    String where = ContactsContract.Data._ID + " = ?" ;
    String[] params = new String[] {_id};

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
        .withSelection(where, params)
        .withValue(ContactsContract.Data.DISPLAY_NAME, name)
        .withValue(ContactsContract.CommonDataKinds.Phone.DATA, phone)
        .withValue(ContactsContract.CommonDataKinds.Organization.DATA, company)
        .build());

    try {
        cr.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (Exception e) {
        Log.e("ERROR UPDATE: ", e.getMessage());
    }
    this.finish();
    Toast.makeText(getApplicationContext(), "Contact saved", Toast.LENGTH_SHORT).show();
    this.callHomeActivity();
}

1 个答案:

答案 0 :(得分:0)

@ Stacks28:这是我--Pakapun先生

我尝试使用以下代码仅更新联系人的姓名。但是没有任何事情发生!联系人姓名尚未更新。代码有什么问题?

public void editContact(String _id, String name, String phone, String company) {         
    String where =  ContactsContract.Data._ID + " = ? AND " +
            ContactsContract.Data.MIMETYPE + "= ?";
    String[] params = new String[] {_id, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
    ContentResolver cr = getContentResolver();
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
            .withSelection(where, params)
            .withValue(StructuredName.DISPLAY_NAME, name)
            .build());  
    try {           
        cr.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (Exception e) {
        Log.e("ERROR UPDATE: ", e.getMessage());
    }

}