如何从已知联系人获取组名

时间:2015-04-23 18:39:22

标签: android cursor contacts contactscontract

我正在尝试根据字符串从联系人名称中获取组名。我认为这将是一个更常见的问题,但我在谷歌或这里看到的每个答案都已过时,没有答案或通过解释有关群组的所有内容得到错误解答,除了实际问题。再一次,如何获得联系人的群组名称,您已经知道了联系人姓名?

Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext()) {
    String contactname=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
    String contactgroup =  "GET GROUP NAME FROM STRING"(contactname);     
}

phones.close();

1 个答案:

答案 0 :(得分:1)

此方法返回给定联系人姓名的组标题列表:

public List<String> getGroupsTitle(String name, Context context) {

    List<String> groupsTitle = new ArrayList<>();

    String contactId = null;

    Cursor cursorContactId = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID},
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + "=?",
            new String[]{name},
            null);

    if (cursorContactId.moveToFirst()) {
        contactId = cursorContactId.getString(0);
    }

    cursorContactId.close();

    if (contactId == null)
        return null;

    List<String> groupIdList = new ArrayList<>();

    Cursor cursorGroupId = context.getContentResolver().query(
            ContactsContract.Data.CONTENT_URI,
            new String[]{ContactsContract.Data.DATA1},
            String.format("%s=? AND %s=?", ContactsContract.Data.CONTACT_ID, ContactsContract.Data.MIMETYPE),
            new String[]{contactId, ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE},
            null);

    while (cursorGroupId.moveToNext()) {
        String groupId = cursorGroupId.getString(0);
        groupIdList.add(groupId);
    }
    cursorGroupId.close();

    Cursor cursorGroupTitle = getContentResolver().query(
            ContactsContract.Groups.CONTENT_URI, new String[]{ContactsContract.Groups.TITLE},
            ContactsContract.Groups._ID + " IN (" + TextUtils.join(",", groupIdList) + ")",
            null,
            null);

    while (cursorGroupTitle.moveToNext()) {
        String groupName = cursorGroupTitle.getString(0);
        groupsTitle.add(groupName);
    }
    cursorGroupTitle.close();

    return groupsTitle;
}