我怎样才能在Android中联系人的的groupId /组名? [英] How can i get a groupId / GroupName of a Contact in Android?

查看:203
本文介绍了我怎样才能在Android中联系人的的groupId /组名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在Android设备上的通讯录present列表。我想获取所有联系人的相关的组id和组名。我一直在试图用ContactsContract.Groups._ID来获取ID,但我不能够得到它。有人可以提供我其他方式来获得接触的GROUPID?

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?

推荐答案

这是我要做的事。你或许可以浪费时间和找到没有做两个查询更快的解决方案。

This is how I do it. You can probably mess around and find a faster solution by not doing two queries.

我们的想法是使用 GroupMembership.GROUP_ROW_ID 数据表中获取组的行ID。当你有行ID,你用它来查询组表拿到小组的姓名(名称)。

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.

通常情况下, Groups.TITLE 不是一个好名字,你可能要格式化或搜索周围找到更好的东西。

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.

这里是code获得接触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();
    }
}

这里是code拿到小组的标题:

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

这篇关于我怎样才能在Android中联系人的的groupId /组名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆