【问题标题】:How can i get a groupId / GroupName of a Contact in Android?如何在 Android 中获取联系人的 groupId / GroupName?
【发布时间】:2011-05-23 07:15:31
【问题描述】:

我的 Android 设备中存在联系人列表。我想获取所有联系人的关联 groupIds 和 GroupName。我一直在尝试使用 ContactsContract.Groups._ID 来获取 ID,但我无法获取它。有人可以提供其他方式来获取联系人的 groupID 吗?

【问题讨论】:

  • 你看过这个吗?它可能会有所帮助。 stackoverflow.com/questions/3026750/…
  • giZm0 在 GroupMembership 视图中处于正确的轨道...请记住,虽然一个联系人可以属于多个组。

标签: android contacts android-contacts


【解决方案1】:

这就是我的做法。您可以通过不进行两次查询来解决问题并找到更快的解决方案。

这个想法是使用GroupMembership.GROUP_ROW_ID从数据表中获取组的行ID。当您拥有行 id 时,您可以使用它来查询 Groups 表以获取组的名称(标题)。

Groups.TITLE 通常不是一个好名称,您可能需要对其进行格式化或四处搜索以找到更好的名称。

获取联系人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();
    }
}

下面是获取组标题的代码:

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

【讨论】:

  • 一个联系人可能在多个组中,为什么不使用循环来处理这种情况?
  • @vuhung3990 当然可以,这只是一般的想法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 1970-01-01
  • 2016-10-08
  • 2011-09-13
相关资源
最近更新 更多