simplfuzz
simplfuzz

Reputation: 12905

Android - Find a contact by fuzzy/approximate/similarity match

There are ways to find a contact by display name. For e.g. this answer Android - Find a contact by display name

But I need to find contacts with fuzzy match. For e.g. I need to return contact named "Keem" if "Kim" wasn't found.

How do I do that?

Upvotes: 3

Views: 2347

Answers (1)

marmor
marmor

Reputation: 28199

There's no build API that can do fuzzy search over display-names, but you can do it yourself, shouldn't be that hard:

  1. Read all contacts' names from the DB
  2. Use a similarity string compare algorithm like Jaro Winkler to compare with the requested name
  3. Return the best match

For step one, here's the code:

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

For step 2, you can use Jaro Winkler, or some other string distance algorithm, here's a library that can help you: https://github.com/tdebatty/java-string-similarity

Upvotes: 2

Related Questions