我有一个Android联系人列表,我试图检索给定的姓名,中间名和姓氏。我能够检索其他信息,包括电子邮件和电话号码,但当我向内容解析器查询联系人的姓名部分时,我总是得到空值作为回报(即使moveToNext()是执行,意味着从系统中检索记录。)
相关代码:
String id = "Some ID";
// Perform a query to retrieve the contact's name parts
String[] nameProjection = new String[] {
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME,
ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME
};
Cursor nameCursor = mContext.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
nameProjection,
ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID
+ "=?", new String[] { id }, null);
// Retrieve the name parts
String firstName = "", middleName = "", lastName = "";
if(nameCursor.moveToNext()) {
firstName = nameCursor.getString(nameCursor.getColumnIndex(
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
middleName = nameCursor.getString(nameCursor.getColumnIndex(
ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME));
lastName = nameCursor.getString(nameCursor.getColumnIndex(
ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
}
执行这段代码后,字符串为null,但不会抛出异常。我手动检查了几个联系人,所有联系人都填写了给定的姓名,中间名和姓氏。
我在这里做错了什么?
答案 0 :(得分:6)
我发现我错过了MIMETYPE条件,以便从包含名称的聚合表中实际选择行。
我将nameCursor更改为:
Cursor nameCursor = mContext.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
nameProjection,
ContactsContract.Data.MIMETYPE + " = '" +
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "' AND " +
ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID
+ " = ?", new String[] { id }, null);
现在它正在工作:)