6
我有Android設備中存在的聯繫人列表。我想獲取所有聯繫人的關聯groupIds和GroupName。我一直在嘗試使用ContactsContract.Groups._ID來獲取ID,但我無法得到它。有人可以通過其他方式獲得聯繫人的組ID嗎?如何在Android中獲取聯繫人的groupId/GroupName?
我有Android設備中存在的聯繫人列表。我想獲取所有聯繫人的關聯groupIds和GroupName。我一直在嘗試使用ContactsContract.Groups._ID來獲取ID,但我無法得到它。有人可以通過其他方式獲得聯繫人的組ID嗎?如何在Android中獲取聯繫人的groupId/GroupName?
這就是我的做法。通過不做兩個查詢,您可能會陷入混亂並找到更快的解決方案。
這個想法是使用GroupMembership.GROUP_ROW_ID
從數據表中獲取組的行ID。如果您有行ID,則使用它查詢組表以獲取組的名稱(標題)。
通常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();
}
}
你看這個?它可能有幫助。 http://stackoverflow.com/questions/3026750/android-2-0-contact-groups-manipulation – 2011-01-21 05:20:59
giZm0在「GroupMembership」視圖中處於正確軌道......請記住,聯繫人可以屬於更多比一個組。 – eidylon 2013-01-31 20:52:54