I have a found a great code on how to retrieve contact groups from the phone:
final String[] GROUP_PROJECTION = new String[] {ContactsContract.Groups._ID, ContactsContract.Groups.TITLE };
Cursor cursor = getContentResolver().query(ContactsContract.Groups.CONTENT_URI, GROUP_PROJECTION, null, null, ContactsContract.Groups.TITLE);
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Groups._ID));
String gTitle = (cursor.getString(cursor.getColumnIndex(ContactsContract.Groups.TITLE)));
if (gTitle.contains("Group:")) {
gTitle = gTitle.substring(gTitle.indexOf("Group:") + 6).trim();
}
if (gTitle.contains("Favorite_")) {
gTitle = "Favorites";
}
if (gTitle.contains("Starred in Android") || gTitle.contains("My Contacts")) {
continue;
}
arr_groups.add(gTitle);
arr_groupswithid.add(id + "." + gTitle);
}
The result is:
I have no idea why I get more of the same group with different id-s. Maybe as Abhishek suggested it has something to do with contacts stored on sim, phone or synced from Facebook or Gmail.
Ignoring this I have been trying to retrieve the contacts belonging to a specific group, but I never get the correct numbers.
String groupId = "10";
String where = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "="
+ groupId + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'";
Cursor c = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.GroupMembership.RAW_CONTACT_ID,
ContactsContract.Data.DISPLAY_NAME
}, where, null, ContactsContract.Data.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
Log.i("cursorc", c.getCount() + "");
If the groupId==10, I get 7 contacts. If it is ==12, I get 11. If it is ==5, I get 0. All in all 18, which is good, as I have 18 persons in the Coworkers group, see image below.
If the groupId==3, I get 0 contacts. If it is ==9, I get 2. If it is ==13, I get 0. All in all 2, which is good.
If the groupId==1, I get 0 contacts. Where the hell are my Favorites?? It should give me 2.
If the groupId==6, I get 0 contacts. Where the hell are my Frequent Contacts?? It should give me 17.
These are my groups in my phone:
I don't know what to do now.