Search code examples
androidandroid-contactsandroid-cursorandroid-search

Search Contact By Name


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?


Solution

  • I did it by using the following code

    Cursor cursor = getContentResolver().query(
                android.provider.ContactsContract.Contacts.CONTENT_URI,
                new String[] { ContactsContract.Contacts.PHOTO_ID,
                        ContactsContract.Contacts.DISPLAY_NAME,
                        ContactsContract.Contacts._ID },
                ContactsContract.Contacts.HAS_PHONE_NUMBER, null,
                ContactsContract.Contacts.DISPLAY_NAME);
    

    This cursor gives all the contacts that have any phone number and then i save the unique ID in an ArrayList like this

    cursor.moveToFirst();
    
        while (cursor.moveToNext()) {
            contactsID.add(cursor.getString(2));
        }
    

    then on selecting the contact i find the contact numbers using this

    Cursor cursor = getContentResolver()
                        .query(android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                new String[] {
                                        ContactsContract.CommonDataKinds.Phone.NUMBER,
                                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME },
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                        + " = ?",
                                new String[] { contactsID.get(position) }, null);
                contactNumbers = new ArrayList<String>();
                while (cursor.moveToNext()) {
                    contactNumbers.add(cursor.getString(0));
                    Log.d("number", cursor.getString(0));
                }