Android - 通过模糊/近似/相似性匹配查找联系人

时间:2017-06-09 11:22:39

标签: android android-contacts android-contentresolver

有多种方法可以通过显示名称查找联系人。对于例如这个答案Android - Find a contact by display name

但我需要找到模糊匹配的联系人。对于例如如果找不到“Kim”,我需要返回名为“Keem”的联系人。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

没有构建API可以对显示名称进行模糊搜索,但你可以自己做,不应该那么难:

  1. 阅读所有联系人'来自DB的名称
  2. 使用像Jaro Winkler这样的相似性字符串比较算法来比较所请求的名称
  3. 返回最佳匹配
  4. 对于第一步,请输入以下代码:

    Map<String, Long> contacts = new HashMap<String, Long>();
    
    String[] projection = {Contacts._ID, Contacts.DISPLAY_NAME};
    // use null if you want to include hidden contacts
    String selection = Contacts.IN_VISIBLE_GROUP + "=1"; 
    Cursor cur = cr.query(Contacts.CONTENT_URI, projection, selection, null, null);
    
    while (cur != null && cur.moveToNext()) {
        long id = cur.getLong(0);
        String name = cur.getString(1);
        contacts.put(name, id);
    }
    if (cur != null) {
        cur.close();
    }
    

    对于第2步,您可以使用Jaro Winkler或其他一些字符串距离算法,这里有一个可以帮助您的库: https://github.com/tdebatty/java-string-similarity