Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get a groupId / GroupName of a Contact in Android?

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?

like image 238
Balvant Avatar asked Dec 10 '10 05:12

Balvant


People also ask

Is there a way to group contacts on phone?

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.


1 Answers

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();
    }
}
like image 104
giZm0 Avatar answered Sep 30 '22 08:09

giZm0