删除组中的所有联系人

时间:2011-12-14 11:55:07

标签: android android-contacts

我正在尝试删除已定义组中的所有联系人,但我不知道如何从联系人表和组表中进行联接(如果可能的话)。

ContentResolver cr = getContentResolver();
String where = ContactsContract.Groups.TITLE  + " =='LolGroup'"; 

Cursor cursor = cr.query(
    ContactsContract.Contacts.CONTENT_URI, null, where, null, null);
while (cursor.moveToNext()) {
    String lookupKey = cursor.getString(
            cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
    Uri uri = Uri.withAppendedPath(
        ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
    cr.delete(uri, null, null);
}

当然它给了我一个错误,因为联系人组中没有“标题”,但如果我使用ID加入,我应该得到我想要的。

知道如何加入吗?

1 个答案:

答案 0 :(得分:0)

看起来很奇怪,因为ContactsContract.Contacts没有ContactsContract.Groups.TITLE列。所以我认为您可以使用所需的组标题获取组ID,然后使用组ID搜索联系人。这个想法可能如下:

    public String getGroupIdByTitle(String groupTitle){ 
        try {
            cursor = mContentResolver.query(
                 ContactsContract.Groups.CONTENT_URI, 
                    new String[] {Groups._ID}, 
                    Groups.TITLE + "=?", 
                    new String[]{groupTitle}, 
                    null);

                    while (cursor.moveToNext()){
                       return cursor.getString(cursor.getColumnIndex(0);
                    }

        } finally {
            if (cursor!=null) cursor.close();
        }

        return "";
    }

    public String getGroupIdOfContact(String lookupKey) {

    String where = String.format("%s=? AND %s=?", Data.LOOKUP_KEY, Data.MIMETYPE);
    String[] whereArgs = {lookupKey, GroupMembership.CONTENT_ITEM_TYPE};

    String groupRowId = "";
        Cursor cursor = mContentResolver.query(
                Data.CONTENT_URI, 
                new String[]{GroupMembership.GROUP_ROW_ID}, 
                where, whereArgs, null);
        try {
            if (cursor.moveToNext()) {
              return cursor.getString(cursor.getColumnIndex(GroupMembership.GROUP_ROW_ID));
            } 

        } finally {
            if (cursor!=null) cursor.close();
        }

return "";
    }

    public void deleteContactByGroupTitle(String groupTitle) {

        String targetGroupId = getGroupIdByTitle(groupTitle);

        Cursor cursor = null;
        try {
            cursor = mContentResolver.query(Contacts.CONTENT_URI, null, null, null, null);

            while (cursor.moveToNext()){
            String lookupKey = cursor.getString(cursor.getColumnIndex(Contacts.LOOKUP_KEY));
                String groupId = getGroupIdOfContact(lookupKey);
                if (targetGroupId.equals(groupId)){
                       //TODO. delete this contact
                }
            }

        } finally {
            if (cursor!=null) cursor.close();
        }

    }

上面的代码没有经过测试,但我认为基本的想法是一样的。