How to search for contacts in android with partial phone number

1.9k Views Asked by At

I am trying to do fuzzy search of contacts in my android application with partial phone number, with below code. But my search function always ends in no result.

For example,

I have contact with phone number 1234567890 with name as "example".

fuzzySearch("4567"); should have return with contact named "example".

Can some please point me where am I wrong? I have checked here. But ended in run-time sql query error.

public ArrayList<Contact> fuzzySearch(String match) {
    private static final String SELECTION = Phone.NUMBER + " LIKE ? COLLATE NOCASE";

    Uri uri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(match));

    String[] projectionFields = new String[]{ContactsContract.Contacts._ID, Phone.NUMBER};

    CursorLoader cursorLoader = null;

    ArrayList<Contact> listContacts = new ArrayList<>();

    if(match.trim().length() == 0){
       return listContacts;
    }else {
        cursorLoader = new CursorLoader(context, uri, projectionFields, SELECTION, new String[]{"%"+match+"%"}, Phone.NUMBER);
    }

    Cursor c = cursorLoader.loadInBackground();

    final Map<String, Contact> contactsMap = new HashMap<>(c.getCount());

    if (c.moveToFirst()) {
        int idIndex = c.getColumnIndex(ContactsContract.Contacts._ID);
        int nameIndex = c.getColumnIndex(Phone.NUMBER);

        do {
            String contactId = c.getString(idIndex);
            String contactDisplayName = c.getString(nameIndex);
            Contact contact = new Contact(contactId, contactDisplayName);
            contactsMap.put(contactId, contact);
            listContacts.add(contact);
        } while (c.moveToNext());
    }

    c.close();
    return listContacts;
}
1

There are 1 best solutions below

0
marmor On

use PhoneLookup instead of phone. because you already encode the search key into the URL, you don't need SELECTION, remove it.

   Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(match));
   Cursor cur = resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME,PhoneLookup.NUMBER, PhoneLookup.CONTACT_ID}, null, null, null);