以下函数将电话号码作为输入参数(例如 +436641234567 或 +436641234567)并在联系人数据库中执行两次查找:首先,识别属于该号码的用户(这已经有效),然后使用用户的 id获取此联系人分配到的所有组(这不起作用)。测试(再次)返回正确的 id,但是,该组为“null”。
public String getNameGroupByNumber(Context context, String number) {
String name = "?";
String contactId = "0";
String group = "0";
String test = "0";
// Step 1: LookUp Name to given Number
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] contactProjection = new String[] {BaseColumns._ID, ContactsContract.PhoneLookup.DISPLAY_NAME };
Cursor contactLookup = contentResolver.query(uri, contactProjection, null, null, null);
try {
if (contactLookup != null && contactLookup.getCount() > 0) {
contactLookup.moveToNext();
name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
contactId = contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
}
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
Log.d(TAG, "Name: " +name + " ContactId: " + contactId); // works as expected
// Step 2: Lookup group memberships of the contact found in step one
Uri groupURI = ContactsContract.Data.CONTENT_URI;
String[] groupProjection = new String[]{ ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID , ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID};
Cursor groupLookup = contentResolver.query(groupURI, groupProjection, ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID+"="+contactId, null, null);
try {
if (groupLookup != null && groupLookup.getCount() > 0) {
groupLookup.moveToNext();
test = groupLookup.getString(groupLookup.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
group = groupLookup.getString(groupLookup.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID));
Log.d(TAG, "Group found with Id: " + test + " and GroupId: " + group); // test is again the contactID from above but group is null
}
} finally {
if (groupLookup != null) {
groupLookup.close();
}
}
return name;
}