Search code examples
androidcursorcontactscontactscontract

How to get group name from a known contact


I am trying to get the group name from a contact name based on a string. I thought this would be a more common question but every answer I have seen on google or here is outdated, has no answers or is incorrectly answered by explaining everything about groups except what the actual question ask. Once again, how do you get the group name of a contact where you already know the contacts name?

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();

Solution

  • This method returns the list of group title given a contact name:

    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;
    }