检索联系人

时间:2018-11-20 10:04:19

标签: android

我也尝试获取电话号码,但我也不知道如何使用此代码。我正在使用的代码请告诉我如何通过具有相同ID的相同代码获取数字

// method to get name, contact id, and birthday
private Cursor getContactsBirthdays() {
    Uri uri = ContactsContract.Data.CONTENT_URI;

    String[] projection = new String[] {
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Event.CONTACT_ID,
            ContactsContract.CommonDataKinds.Event.START_DATE
    };

    String where =
            ContactsContract.Data.MIMETYPE + "= ? AND " +
            ContactsContract.CommonDataKinds.Event.TYPE + "=" + 
            ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
    String[] selectionArgs = new String[] { 
        ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE
    };
    String sortOrder = null;
    return managedQuery(uri, projection, where, selectionArgs, sortOrder);
}

// iterate through all Contact's Birthdays and print in log
Cursor cursor = getContactsBirthdays();
int bDayColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
while (cursor.moveToNext()) {
    String bDay = cursor.getString(bDayColumn);
    Log.d(TAG, "Birthday: " + bDay);
}

1 个答案:

答案 0 :(得分:0)

您需要首先获取具有生日的所有联系人ID的列表,然后查询所有这些联系人的电话,然后打印合并的结果。

Cursor cursor = getContactsBirthdays();

// get contact-ids for phones query
List<String> ids = new ArrayList<>();
while (cursor.moveToNext()) {
    ids.add(cursor.getString(1));
}
String[] projection = new String[] { Phone.NUMBER, Phone.CONTACT_ID };

StringBuilder where = new StringBuilder(Data.MIMETYPE + " = " Phone.CONTENT_ITEM_TYPE + " AND " + Contacts.CONTACT_ID + " IN (");
for (String id : ids) {
    where.append(id).append(",");
}
where.deleteCharAt(where.length() - 1);
where.append(")");


Cursor cur2 = getContentResolver().query(Data.CONTENT_URI, projection, where.toString(), null, null);
Map<Long, String> contactIdToPhone = new HashMap<>();
while (cur2.moveToNext()) {
    contactIdToPhone.put(cur2.get(1), cur2.get(0));
}
cur2.close();

cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
    Long id = cursor.getLong(1);
    Log.i(TAG, "Birthday: id=" + id + ", name=" + cursor.getString(0) + ", date=" + cursor.getString(2) + ", phone=" + contactIdToPhone.get(id));
}
cursor.close();