更新多个电话号码联系人

时间:2012-08-20 15:02:35

标签: android android-contentprovider android-contacts contactscontract

我需要为同一个联系人更新多个电话号码。我只能更新一个电话号码,但我不知道如何更新2例如

这是我的代码......

String stEtPhone = etPhone.getText().toString();

values.clear();
String phoneWhere = ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?";
String[] phoneWhereParams = new String[]{String.valueOf(idContacto),ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,stEtPhone);
cr.update(ContactsContract.Data.CONTENT_URI, values, phoneWhere, phoneWhereParams); 

1 个答案:

答案 0 :(得分:1)

您的代码应更新与WHERE子句匹配的每一行。如果你知道有额外的行应该匹配但不是,那么那里有些错误。

一种可能的测试方法:您可能首先要查询与给定ContactsContract.CommonDataKinds.Phone.NUMBER匹配ContactsContract.Data.RAW_CONTACT_ID的内容,并查看返回的内容。

如果有必要(虽然我不确定这与您正在做的事情有多么不同),请迭代结果while(cursor.moveToNext()),如果电话号码与您尝试更新的电话号码相匹配, update它。

请注意,这是未经测试的袖口代码,因此可能存在小错误,如果您真的这样做,则需要使用List<ContentProviderOperation>然后执行批处理操作,而不是一个接一个地做这个。

ContentResolver resolver = getContentResolver();
String[] columnsToReturn = {Data._ID, ContactsContract.CommonDataKinds.Phone.NUMBER}
// This should return all of the phone numbers that match your criteria
Cursor cursor = resolver.query(ContactsContract.Data.CONTENT_URI, columnsToReturn, phoneWhere, phoneWhereParams, null);

while(cursor != null && cursor.moveToNext()){
    // This code doesn't do this, but you might want to see how many items 
    // are returned in your cursor here to verify that you're getting what 
    // you should for some known case..

    // I'm using the row ID here (Data._ID) to update, instead of your initial WHERE
    resolver.update(ContactsContract.Data.CONTENT_URI, values, Data._ID + "=?", cursor.getString(cursor.getColumnId(Data._ID));

}

如果您在UPDATE语句中正确设置了所有内容,则甚至不必首先执行查询。

您可能还会发现附加到this问题的代码块很有用。

相关问题