Search code examples
androidcursorandroid-contactsphone-number

Get Contact by Phone number on Android


I know how I can get all contacts in Android , and how to get their phone number.

What I cant seem to figure out is how to get a contact by phone number...

This is my current piece of code I wrote to test which phone numbers are available:

// Create a cursor
    Cursor cursor = Base.contentResover().query(Phone.CONTENT_URI, null, null,
            null, null);

    if (cursor.moveToNext()) {
        Log.d("CALLOG", cursor.getString(cursor.getColumnIndexOrThrow(Phone.NUMBER)));
    }

The problem is that i only get a few phone numbers returned, while i expect to get all... What am I doing wrong?


Solution

  • I dont think there is anything wrong with the snippet that you had pasted. Try using a while loop to LOG all the phone numbers.

    Regarding your requirement to fetch a contact by Phone Number.Try using the following snippet

    Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber)); 
    resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME,PhoneLookup._ID...
    

    Use the _ID to determine the contact.

    Why to use PhoneLookup instead of Phone?

    • The PhoneLookup is highly optimised in terms of its searches.

    • Phone numbers can be entered in the contacts database with fillers like "(",")","-" etc PhoneLookup
      helps to decouple these fillers and compare only the phone number.

    • Comparing the values from Phone will not fetch you any result.

    • It provides various other phone number related info. (HAS_PHONE_NUMBER,TIMES_CONTACTED,DISPLAY_NAME etc)

    Hope that helps. Let me know if you need anything else.