【问题标题】:How to get the first name of a contact in Android?如何在 Android 中获取联系人的名字?
【发布时间】:2021-06-25 09:44:39
【问题描述】:

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

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

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

【问题讨论】:

    标签: android kotlin android-contacts


    【解决方案1】:

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

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

    这里的代码 sn-p 用于从联系人数据库中获取所有给定名称:

    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();
    

    更新

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

    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, projection, selection, null, 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;
        }
    }
    

    【讨论】:

    • 使用 StructuredName 行可以获取联系人的电话号码吗?
    • 如果您需要来自多个 mimetype(姓名和电话)的数据,您可以在 Data.CONTENT_URI 表上查询,并选择您需要的特定 mimetypes
    • 我没有找到任何类似的样本。如果不是太麻烦的话,你能给我举个例子来说明它是如何完成的吗?谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-09-13
    • 2011-05-17
    • 2021-01-06
    • 1970-01-01
    • 2012-10-11
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多