Search Contact By Name

Rohan Kandwal picture Rohan Kandwal · Sep 3, 2013 · Viewed 11.9k times · Source

I am trying to create a Custom Contact app which displays only those contacts that have Contact Number. First of all, is there any automated way to do it? Suppose not, then I am trying to search a contact by its name e.g. Rohan.

Here is the code :-

Cursor photoCursor = getContentResolver().query(
            android.provider.ContactsContract.Contacts.CONTENT_URI,
            new String[] { ContactsContract.Contacts.PHOTO_ID,
                    ContactsContract.Contacts.DISPLAY_NAME },
            ContactsContract.Contacts.DISPLAY_NAME + " = ?",
            new String[]{"Rohan"}, null);
    photoCursor.moveToFirst();
    while (photoCursor.moveToNext()) {
        Log.d("Photo Thumbnail", "" + photoCursor.getString(1));
    }

Although the contact exists, I am not getting any Log, if I remove Selection & Selection Args I see Rohan in the log. What am I doing wrong?

Answer

Joshua Pinter picture Joshua Pinter · May 10, 2018

Simple Solution for Searching Partial Display Name.

ContentResolver contentResolver = getCurrentActivity().getContentResolver();

String   whereString = "display_name LIKE ?";
String[] whereParams = new String[]{ "%" + searchText + "%" };

Cursor contactCursor = contentResolver.query(
        ContactsContract.Data.CONTENT_URI,
        null,
        whereString,
        whereParams,
        null );

while( contactCursor.moveToNext() ) {

    int contactId = getIntFromCursor( contactCursor, ContactsContract.Data.CONTACT_ID );

    Log.d( "Contact ID", contactId)

}

contactCursor.close();