Search code examples
androidandroid-contentproviderandroid-contactsandroid-cursorandroid-contentresolver

Get contact Number as it is from Contact list


I ran into the problem while fetching contact using ContentResolver.

Contact list shows contact with spaces, but after fetching contact using content resolver it removing all spaces.

Contact list : +91 XXXXX XXXXX

After fetch : +91XXXXXXXXXX (Wrong removing spaces)

However it's not removing character if number is

Contact list : +1 (XXX) XXX-XXXX

After fetch : +1 (XXX) XXX-XXXX (Correct as it is)

Below code is used to fetch contact

 String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
 String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};
 Cursor cursor = getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
                null, null, order);

Solution

  • The CommonDataKinds.Phone.NUMBER field can contain a number in any format, not necessarily a user displayable friendly one. To format the number for display to the user, you can use the libphonenumber package by Google, which parses a phone number and allows you to format it into either a user friendly format, or the canonical e164 format useful for storing and comparing.

    https://github.com/googlei18n/libphonenumber