android更新联系人姓名、号码

原文链接: http://www.cnblogs.com/dotc/archive/2012/09/13/2683453.html
    private void updatePhoneInfo(String phoneName, String phoneNumber) {
        //获取需要修改的联系人信息,该 Uri 信息是从其他 Activity 中传过来的,因此这里只是简单的获得
        final Intent intent = getIntent();
        Uri data = intent.getData();
        final long contactId = ContentUris.parseId(data);
        
        //查找联系人语句 SQL 中的 where selection 语句,通过 RAW_CONTACT_ID 选取需要修改的记录
        final String nameSelection = StructuredName.RAW_CONTACT_ID + " = ? AND "
                + Data.MIMETYPE + " = ?";
        final String[] nameSelectionArgs = new String[] { String.valueOf(contactId),
                StructuredName.CONTENT_ITEM_TYPE };
        final String numberSelection = Phone.RAW_CONTACT_ID + " = ? AND "
                + Data.MIMETYPE + " = ?";
        final String[] numberSelectionArgs = new String[] {
                String.valueOf(contactId), Phone.CONTENT_ITEM_TYPE };

        //存储操作语句的容器
        ArrayList ops = new ArrayList();
        
        //ContentProviderOperation 提供了 SQL 的增(add)、删(delete)、改(update)的基本操作,只要设置好条件和修改语句就可以了
        // update contact's name
        ContentProviderOperation.Builder builder =  ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);        
        builder.withSelection(nameSelection, nameSelectionArgs);
        builder.withValue(StructuredName.FAMILY_NAME, null);
        builder.withValue(StructuredName.DISPLAY_NAME, phoneName);        
        ops.add(builder.build());
        
        // update contact's phone number
        builder =  ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
        builder.withSelection(numberSelection, numberSelectionArgs);
        builder.withValue(Phone.NUMBER, phoneNumber);
        ops.add(builder.build());
        
        try {
            //一次性应用上述修改操作
            getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (OperationApplicationException e) {
            e.printStackTrace();
        }

    }

Contacts的增删查改的操作方法可以参考android的文档:http://developer.android.com/reference/android/provider/ContactsContract.Data.html

转载于:https://www.cnblogs.com/dotc/archive/2012/09/13/2683453.html

你可能感兴趣的:(android更新联系人姓名、号码)