Search code examples
androidandroid-contacts

ContactsContract.CommonDataKinds.Phone.NUMBER does not work as expected


I have been searching for a very fast way to load contacts in my android application. I came across this answer and it worked! My contacts load super fast now.

There is only one problem however, the solution involves using the array below to query the contacts:

private static final String[] PROJECTION = new String[] {
        ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
        ContactsContract.Contacts.DISPLAY_NAME,
        ContactsContract.CommonDataKinds.Phone.NUMBER
};

Obviously, ContactsContract.CommonDataKinds.Phone.NUMBER retrieves the phone number.

The problem I'm currently facing is that this field only retrieves phone numbers with country codes. Therefore, it can easily detect +2347000000000 but not 07000000000. I want to be able to detect phone numbers without country codes.

What do I do?


Solution

  • You can use Google's libphonenumber library in order to add/remove country codes to phones, see here: https://github.com/google/libphonenumber (read the readme regarding usage in Android)

    here's a relevant snippet for your use-case:

    There are a few formats supported by the formatting method, as illustrated below:
    
    // Produces "+41 44 668 18 00"
    System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.INTERNATIONAL));
    // Produces "044 668 18 00"
    System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.NATIONAL));
    // Produces "+41446681800"
    System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.E164));
    You could also choose to format the number in the way it is dialed from another country:
    
    // Produces "011 41 44 668 1800", the number when it is dialed in the United States.
    System.out.println(phoneUtil.formatOutOfCountryCallingNumber(swissNumberProto, "US"));```