我编写了以下函数以检索属于 ID 为“contactID”的联系人的一个电话号码。
获取电话号码的函数:
private String getContactPhone(String contactID) {
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = null;
String where = ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?";
String[] selectionArgs = new String[] { contactID };
String sortOrder = null;
Cursor result = managedQuery(uri, projection, where, selectionArgs, sortOrder);
if (result.moveToFirst()) {
String phone = result.getString(result.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (phone == null) {
result.close();
return null;
}
result.close();
return phone;
}
result.close();
return null;
}
如何调用此函数:
ArrayList<Contact> resultContacts = new ArrayList<Contact>();
Cursor result = null;
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
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;
result = managedQuery(uri, projection, where, selectionArgs, sortOrder);
while (result.moveToNext()) {
Long id = result.getLong(result.getColumnIndex(ContactsContract.Contacts._ID));
String phone = getContactPhone(String.valueOf(id));
...
}
...
不幸的是,它不起作用。如果我使用从“ContactsContract.Contacts._ID”获得的值调用此函数,我会得到 null。为什么会这样?怎么了?
编辑:我曾经将 Contacts._ID 映射到 CommonDataKinds.Phone.CONTACT_ID - 但没有用。但是现在我将 Contacts.DISPLAY_NAME 映射到 CommonDataKinds.Phone.DISPLAY_NAME 并且它突然起作用了——很奇怪,不是吗?但我宁愿映射 ID 而不是显示名称。所以这个问题仍然是热门话题。这可能是由于这些表中的不同 ID 造成的吗?这不是有查找 ID 的原因吗?
最佳答案
要获取第一部分中的联系人 ID,您应该使用:
ContactsContract.Data.CONTACT_ID
代替:
ContactsContract.Contacts._ID
所以投影应该是:
String[] projection = new String[] {
ContactsContract.Data.CONTACT_ID,
ContactsContract.CommonDataKinds.Event.CONTACT_ID,
ContactsContract.CommonDataKinds.Event.START_DATE,
};
然后当然得到正确的行:
Long id = result.getLong(result.getColumnIndex(ContactsContract.Data.CONTACT_ID));
关于java - 在 Android 中使用 ContactsContract 检索电话号码 - 功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8735683/