我在这里遇到了一个问题,因为我刚开始为Android开发。我从官方Android网站“http://developer.android.com/training/contacts-provider/retrieve-names.html”下载了样本,该网站基本上能够检索显示手机中的所有联系人。我想添加的功能是只显示某个组中的联系人,例如“朋友”(硬编码)。
据我缩小范围,我必须更改选择部分
final static String SELECTION =
(Utils.hasHoneycomb() ? Contacts.DISPLAY_NAME_PRIMARY : Contacts.DISPLAY_NAME) +
"<>''" + " AND " + Contacts.IN_VISIBLE_GROUP + "=1";
这样的事情
final static String SELECTION =
Contacts.GroupID = "Friends";
这给了我错误,因为它无法找到列。
我非常渴望探索Android的潜力,但那令我头疼。
答案 0 :(得分:6)
有两种获取群组联系人列表的方法。首先,我想你有GroupId并希望获得相关的联系人列表。
String[] projection = {
ContactsContract.Groups._ID,
ContactsContract.Groups.TITLE,
ContactsContract.Groups.ACCOUNT_NAME,
ContactsContract.Groups.ACCOUNT_TYPE
};
return context.getContentResolver().query(
ContactsContract.Groups.CONTENT_URI, projection, ContactsContract.Groups._ID + "=" + groupId , null, null
);
第二种方式: 我想你想通过常量名称获取特定组的联系人。所以,你改变上面的代码就足够了:
context.getContentResolver().query(
ContactsContract.Groups.CONTENT_URI, projection, ContactsContract.Groups.ACCOUNT_NAME + "='Friends'" , null, null
);
现在您需要特定组的必要详细信息。然后,您可以获取联系人列表:
public static Cursor getContactsOfGroup(Group group) {
// getting ids of contacts that are in this specific group
String where = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "="
+ group.id + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'";
Cursor query = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID
}, where, null, ContactsContract.Data.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
String ids = "";
for (query.moveToFirst(); !query.isAfterLast(); query.moveToNext()) {
ids += "," + query.getString(0);
}
if (ids.length() > 0) {
ids = ids.substring(1);
}
// getting all of information of contacts. it fetches all of number from every one
String[] projection = new String[]{
"_id",
"contact_id",
"lookup",
"display_name",
"data1",
"photo_id",
"data2", // number type: 1:home, 2:mobile, 3: work, else : other
};
String selection = "mimetype ='" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'"
+ " AND account_name='" + group.accountName + "' AND account_type='" + group.accountType + "'"
+ " AND contact_id in (" + ids + ")";
return context.getContentResolver().query(BASE_URI, projection, selection, null, null);
}
注意,在此方法的第二次提取中,我们检查 accountName 和 accountType 以确保此记录与此组相关,因为可能存在一些存储的记录另一个应用程序,如 WhatsApp 。我们不喜欢那些。 OK?
我希望对你有用。