androidlocaleandroid-contactscontactscontract

Fetch contacts ignoring accents


I fetch contacts from the phone as below. I would like to ignore accent for exemple the name "Jérome" would be return either for search "jero" or "jéro".

 var contacts = listOf<Contact>()

        val displayNameProjection = arrayOf(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI,  ContactsContract.Contacts.DISPLAY_NAME_PRIMARY)
        val whereName =  ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " LIKE ?"
        val whereNameParams = arrayOf( "%" + search + "%")
        val contactCursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI,
                displayNameProjection, whereName, whereNameParams,ContactsContract.Contacts.DISPLAY_NAME_PRIMARY)

        contactCursor?.let { cursor ->
            contacts = generateSequence { if (cursor.moveToNext()) cursor else null }
                    .take(10)
                    .map {
                        Contact( it.getString(it.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY)),
                                it.getString(it.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI)))
                    }
                    .toList()


            cursor.close()
        }

Solution

  • Use the CONTENT_FILTER_URI API to quickly search contacts by name, this should handle accents automatically for you:

    String name = "jero";
    Uri searchUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode(name));
    Cursor cur = getContentResolver().query(searchUri, null, null, null, null);
    DatabaseUtils.dumpCursor(cur);
    if (cur != null) cur.close();