如何更新现有联系人?

20

我有一个现有的联系人,我需要为该现有联系人添加一个工作地址。 我使用以下代码,但它不起作用。

String selectPhone = Data.CONTACT_ID + "=? AND " + Data.MIMETYPE + "='" + 
    ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE + 
    "'" + " AND " + ContactsContract.CommonDataKinds.StructuredPostal.TYPE + "=?"; 
String[] phoneArgs = new String[]
    {String.valueOf(ContactId), String.valueOf(
    ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK)}; 
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI) 
    .withSelection(selectPhone, phoneArgs) 
    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, STREET)
    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, CITY) 
    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, REGION)
    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, POSTCODE) 
    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, COUNTRY)  
    .build()); 
this.context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); 

有什么解决方法吗?


我遇到了同样的问题,但是没有任何作用,有人可以帮忙吗? - user788511
6个回答

16
        /**
             * @param name name of the contact
             * @param number mobile phone number of contact
             * @param email work email address of contact
             * @param ContactId id of the contact which you want to update
             * @return true if contact is updated successfully<br/>
             *         false if contact is not updated <br/>
             *         false if phone number contains any characters(It should contain only digits)<br/>
             *         false if email Address is invalid <br/><br/>
             *         
             *  You can pass any one among the 3 parameters to update a contact.Passing all three parameters as <b>null</b> will not update the contact        
             *  <br/><br/><b>Note: </b>This method requires permission <b>android.permission.WRITE_CONTACTS</b><br/>
             */

            public boolean updateContact(String name, String number, String email,String ContactId) 
            {
                boolean success = true;
                String phnumexp = "^[0-9]*$";

                try
                {
                      name = name.trim();
                      email = email.trim();
                      number = number.trim();

                if(name.equals("")&&number.equals("")&&email.equals(""))
                 {
                    success = false;
                 }
                else if((!number.equals(""))&& (!match(number,phnumexp)) )
                 {
                    success = false;
                 }
                else if( (!email.equals("")) && (!isEmailValid(email)) )
                {
                    success = false;
                }
                else 
                {
                    ContentResolver contentResolver  = activity.getContentResolver();

                    String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 

                    String[] emailParams = new String[]{ContactId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE}; 
                    String[] nameParams = new String[]{ContactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE}; 
                    String[] numberParams = new String[]{ContactId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE}; 

                    ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<android.content.ContentProviderOperation>();

                 if(!email.equals(""))  
                 {
                     ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
                          .withSelection(where,emailParams)
                          .withValue(Email.DATA, email)
                          .build());
                 }

                 if(!name.equals(""))
                 {
                     ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
                          .withSelection(where,nameParams)
                          .withValue(StructuredName.DISPLAY_NAME, name)
                          .build());
                 }

                 if(!number.equals(""))
                 {

                     ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
                          .withSelection(where,numberParams)
                          .withValue(Phone.NUMBER, number)
                          .build());
                 }
                    contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
                 }
                }
                catch (Exception e) 
                {
                 e.printStackTrace();
                 success = false;
                }
                return success;
            }



    // To get COntact Ids of all contact use the below method 

    /**
         * @return arraylist containing id's  of all contacts <br/> 
         *         empty arraylist if no contacts exist <br/><br/>
         * <b>Note: </b>This method requires permission <b>android.permission.READ_CONTACTS</b>
         */
        public ArrayList<String> getAllConactIds()
        {
            ArrayList<String> contactList = new ArrayList<String>();

             Cursor cursor = activity.managedQuery(ContactsContract.Contacts.CONTENT_URI, null, null, null, "display_name ASC");

                if (cursor != null) 
                {
                    if (cursor.moveToFirst()) 
                    {
                       do
                       {
                           int _id = cursor.getInt(cursor.getColumnIndex("_id"));
                           contactList.add(""+_id);

                       }
                       while(cursor.moveToNext());
                    }
                }

            return contactList;
        }


private boolean isEmailValid(String email) 
    {
        String emailAddress = email.toString().trim();
        if (emailAddress == null)
            return false;
        else if (emailAddress.equals(""))
            return false;
        else if (emailAddress.length() <= 6)
            return false;
        else {
            String expression = "^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\\.([a-z][a-z|0-9]*(\\.[a-z][a-z|0-9]*)?)$";
            CharSequence inputStr = emailAddress;
            Pattern pattern = Pattern.compile(expression,
                    Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(inputStr);
            if (matcher.matches())
                return true;
            else
                return false;
        }
    }

    private boolean match(String stringToCompare,String regularExpression)
    {
        boolean success = false;
        Pattern pattern = Pattern.compile(regularExpression);
        Matcher matcher = pattern.matcher(stringToCompare);
        if(matcher.matches())
            success =true;
        return success;
    }

1
如果只有一个电话号码、姓名或电子邮件,则此答案是正确的。如果有多个电话号码,例如,您应该添加String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.Phone.NUMBER + " = ?"; String[] numberParams = new String[]{ContactId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, oldPhoneNumber};以正确修改一个联系人中的所有电话号码。 - TranHieu

4

//很抱歉我的英文不好 //在第一篇帖子中,您似乎忘记在操作中添加 MimeType

String selectPhone = Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "='" + 
                    ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE +  "'" ; 
                String[] phoneArgs = new String[]{String.valueOf(rawContactId)}; 
                ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI) 
                    .withSelection(selectPhone, phoneArgs) 
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK)
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, STREET)
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, CITY) 
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, REGION)
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, POSTCODE) 
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, POSTCODE) 

**

//只需要添加这一行代码 .withValue(Data.MIMETYPE, "vnd.android.cursor.item/postal-address_v2")

**

     .build());
this.context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

请检查这个并让我知道结果。

1
每个字段(电子邮件、姓名、地址)都有其自己的 MIME 类型,您应该使用它来更新该字段。
我们将使用数据表,其中每个 Data.RAW_CONTACT_ID 表示关于某个联系人的详细信息。
因此,我们需要找到 Data.RAW_CONTACT_ID,其中 ID 是要编辑的联系人的 ID。
希望这段代码对您有所帮助。
    String selectPhone = Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "='" + 
                        ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE +  "'" ; 
                    String[] phoneArgs = new String[]{String.valueOf(rawContactId)}; 
                    ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI) 
                        .withSelection(selectPhone, phoneArgs) 
                        .withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK)
                        .withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, STREET)
                        .withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, CITY) 
                        .withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, REGION)
                        .withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, POSTCODE) 
                        .withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, POSTCODE)  
                        .build());
this.context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

如果创建了一个新联系人,但没有地址,并且现在想要为该联系人添加地址。在这种情况下,请使用与上面相同的查询,但只需将newUpdate更改为newInsert,因为这样的行尚不存在。

1

终于我找到了合适的解决方案...非常感谢这个如何修改现有联系人

秘诀在于,您必须传递两个值给.withSelection,如下所示:

.withSelection(Data.RAW_CONTACT_ID + " = ?", new String[] {String.valueOf(id)})
.withSelection(Data._ID + " = ?", new String[] {mDataId})

通过以下方式获取Data._ID值的mDataId:

Cursor mDataCursor = this.context.getContentResolver().query(
                        Data.CONTENT_URI,
                        null,
                        Data.RAW_CONTACT_ID + " = ? AND " + Data.MIMETYPE + " = ?",
                        new String[] { String.valueOf(id), ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE},
                        null);

                if(mDataCursor.getCount() > 0) {
                    mDataCursor.moveToFirst();
                    mDataId = getCursorString(mDataCursor, Data._ID);
                    MLog.v("Data", "Found data item with MIMETYPE");                            
                    mDataCursor.close();

                } else {
                    MLog.v("Data", "Data doesn't contain MIMETYPE");
                    result = ERROR;
                    mDataCursor.close();
                } 

而 getCursorString 方法大致如下:

private static String getCursorString(Cursor cursor, String columnName) {
        int index = cursor.getColumnIndex(columnName);
        if(index != -1) return cursor.getString(index);
        return null;
    }

这就是诀窍..


0

在选择语句中,应该使用“Data.RAW_CONTACT_ID”而不是“Data.CONTACT_ID”。


-1

这并不理想,我之前尝试过,但它不符合我的应用要求。 - user788511

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接