如何在Android中获取联系人的名字?

问题描述

我正在尝试使用 ContactsContract 获取我的联系人的信息,而我需要做的是仅获取联系人的名字。我使用了 ContactsContract.CommonDataKinds.Phone.disPLAY_NAME 但这也获得了名字和姓氏,而我只想要名字。

我尝试使用 ContactsContract.CommonDataKinds.Structuredname.GIVEN_NAME 但不是获取名称,而是获取一个数字。

我还没有找到仅获取联系人名字的确切方法。有什么想法吗?

解决方法

您尚未共享代码,但听起来您正在查询表 Phone.CONTENT_URI 并尝试通过 StructuredName.GIVEN_NAME 获取字段。

这是不可能的,因为 Phone.CONTENT_URI 只会返回电话行,而不是 StructuredName 行。

这是从联系人数据库中获取所有给定名称的代码片段:

String[] projection = new String[]{StructuredName.CONTACT_ID,StructuredName.GIVEN_NAME};
String selection = Data.MIMETYPE + "='" + StructuredName.CONTENT_ITEM_TYPE + "'";

Cursor c = getContentResolver().query(Data.CONTENT_URI,projection,selection,null,null);

DatabaseUtils.dumpCursor(c);
c.close();

更新

以下是一些关于如何在单个查询中查询多个 mimetypes 的示例代码。 在这个例子中,我为数据库中的每个联系人创建了一个从 的映射:

Map<Long,List<String>> contacts = new HashMap<Long,List<String>>();

String[] projection = {Data.CONTACT_ID,Data.DISPLAY_NAME,Data.MIMETYPE,StructuredName.GIVEN_NAME,Phone.NUMBER };

// select all rows of type "name" or "phone"
String selection = Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "','" + StructuredName.CONTENT_ITEM_TYPE + "')";
Cursor cur = cr.query(Data.CONTENT_URI,null);

while (cur != null && cur.moveToNext()) {
    long id = cur.getLong(0);
    String name = cur.getString(1);
    String mime = cur.getString(2); // type of row: phone / name

    // get the existing <Given-name,Phone> list from the Map,or create a new one
    List<String> infos;
    if (contacts.containsKey(id)) {
        infos = contacts.get(id);
    } else {
        infos = new ArrayList<String>(2);
        contacts.put(id,infos);
    }

    // add either given-name or phone to the infos list
    switch (mime) {
        case Phone.CONTENT_ITEM_TYPE: 
            infos.set(1,cur.getString(4));
            break;
        case StructuredName.CONTENT_ITEM_TYPE: 
            infos.set(0,cur.getString(3));
            break;
    }
}