I am having list of contacts present in an Android device. I want to fetch the associated groupIds and GroupName of all the contacts. I have been trying to use ContactsContract.Groups._ID to get the ID, but I am not able to get it. Can someone provide me other way to get the groupID of contact?
Create a group On your Android phone or tablet, open the Contacts app . At the bottom, tap Contacts. Create label. Enter a label name and tap OK.
This is how I do it. You can probably mess around and find a faster solution by not doing two queries.
The idea is to get the row id of the group from the Data table using GroupMembership.GROUP_ROW_ID
. When you have the row id you use that to query the Groups table to get the name (Title) of the group.
Often the Groups.TITLE
isn't that good a name and you probably will have to format it or search around to find anything better.
Here is the code to get contact id:
public long getGroupIdFor(Long contactId){
Uri uri = Data.CONTENT_URI;
String where = String.format(
"%s = ? AND %s = ?",
Data.MIMETYPE,
GroupMembership.CONTACT_ID);
String[] whereParams = new String[] {
GroupMembership.CONTENT_ITEM_TYPE,
Long.toString(contactId),
};
String[] selectColumns = new String[]{
GroupMembership.GROUP_ROW_ID,
};
Cursor groupIdCursor = mContext.getContentResolver().query(
uri,
selectColumns,
where,
whereParams,
null);
try{
if (groupIdCursor.moveToFirst()) {
return groupIdCursor.getLong(0);
}
return Long.MIN_VALUE; // Has no group ...
}finally{
groupIdCursor.close();
}
}
And here is the code to get the Title of the group:
public String getGroupNameFor(long groupId){
Uri uri = Groups.CONTENT_URI;
String where = String.format("%s = ?", Groups._ID);
String[] whereParams = new String[]{Long.toString(groupId)};
String[] selectColumns = {Groups.TITLE};
Cursor c = mContext.getContentResolver().query(
uri,
selectColumns,
where,
whereParams,
null);
try{
if (c.moveToFirst()){
return c.getString(0);
}
return null;
}finally{
c.close();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With