Search code examples
androidphone-numberlibphonenumberphonenumberutils

Android - phone number formatting and removing the country/area code


I have built an app where I loop through and collect the users phone contacts, my aim is to then use these numbers and query my parse database and look for records that contain the users contacts (this will be to check if any of the users contacts are a user of my app, a users phone number will be saved to my parse database when they register). The problem I've got is that when collecting the users contacts numbers they are returned in different formats, some +447966000000, some 07966000000, some 07 966000 000000, etc.

My question is, what would be the best way to format my numbers when saving them to the database and retrieving them from the users contacts so that all numbers are saved and retrieved in the same format so that when I do a conditional check on them they will be easy to compare?

I have downloaded phone Number Utils library but I am not sure what in the library could be used to do something like this.



Code so far:

 Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
        while (phones.moveToNext())
        {
            String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            Toast.makeText(getApplicationContext(),name + " " + phoneNumber, Toast.LENGTH_LONG).show();
        }
        phones.close();

Solution

  • You can use PhoneNumberUtils.compare to compare and check if they are same or not.It returns true if they are same ignoring country codes etc.

    Example:

    PhoneNumberUtils.compare(context, 1234567890, +911234567890);
    

    returns true