开发者

How to get the contact group id or name?

I can't get the group name under which the contact is stored. I can get whether it is added in any group as boolean value( IN_VISIBLE_GROUP).I have no idea how to get the group name or id.

     ContentResolver cr = this.getContentResolver();
   开发者_如何学运维     Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                null, null, null);
     if (cur.getCount() > 0) {
     while (cur.moveToNext()) 
            {

                 id = cur.getString(cur
                        .getColumnIndex(BaseColumns._ID));

                String name = cur
                        .getString(cur
                                .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                String group = cur
                .getString(cur
                        .getColumnIndex(ContactsContract.Contacts.IN_VISIBLE_GROUP));

i have tried using ContactsContract.Groups and ContactsContract.Groups and ContactsContract.CommonDataKinds.GroupMembership but that is not the solution.


This is a full version of how to get the group id by its title. Basically it iterates all groups and compare titles to find its id.

private String getGroupId(String groupTitle) {
   Cursor cursor =getContentResolver().query(ContactsContract.Groups.CONTENT_URI,new String[]{ContactsContract.Groups._ID,ContactsContract.Groups.TITLE}, null, null, null);       
    cursor.moveToFirst();
    int len = cursor.getCount();

    String groupId = null;
    for (int i = 0; i < len; i++) {
        String id = cursor.getString(cursor.getColumnIndex(Groups._ID));
        String title = cursor.getString(cursor.getColumnIndex(Groups.TITLE));

        if (title.equals(groupTitle)) {
            groupId = id;
            break;
        }
        cursor.moveToNext();
    }
    cursor.close();

    return groupId;
}


Please change

 ContentResolver cr = this.getContentResolver();

to

 Uri groupURI = ContactsContract.Data.CONTENT_URI;


Cursor cur = cr.query(groupURI , null, null, null, null);


// Now you can get group ID from cursor

String groupRowId =  cur.getString   (cur.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID));


public Integer getGroupId(String groupTitle) {

        String[] PROJECTION = {ContactsContract.Groups._ID};
        String SELECTION = ContactsContract.Groups.TITLE + "=?";

        try (Cursor cursor = mContentResolver.query(ContactsContract.Groups.CONTENT_URI,
                PROJECTION, SELECTION, new String[]{groupTitle}, null)) {

                if (cursor.getCount()>0){
                    cursor.moveToFirst();
                    Integer id= cursor.getInt(0);
                    return id;
                }else
                    return 0;
            }

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜