4

I am trying to find if two phone numbers are same or not (Two same phone number may not be in same format , as +11234567890 is same as 1234567890 and 0011234567890)

I tried PhoneNumberUtils.Compare like this:

if(PhoneNumberUtils.compare("+11234567890", "34567890"))
{
    Toast.makeText(getApplicationContext(), "Are same", Toast.LENGTH_LONG).show();
}

But it returns true for "+11234567890", "34567890" while they are not same.

Is there any better method to do this?

pixel
  • 24,905
  • 36
  • 149
  • 251
Arashdn
  • 691
  • 3
  • 11
  • 25

3 Answers3

10

The best way to solve this problem is using Google's libphonenumber library

PhoneNumberUtil pnu = PhoneNumberUtil.getInstance();

MatchType mt = pnu.isNumberMatch("+11234567890", "34567890");
if( mt == MatchType.NSN_MATCH || mt == MatchType.EXACT_MATCH )
{
    Toast.makeText(getApplicationContext(), "are Same" , Toast.LENGTH_LONG).show();
}

if we use MatchType.SHORT_NSN_MATCH it will return same result as PhoneNumberUtils.compare

Arashdn
  • 691
  • 3
  • 11
  • 25
  • ...which can be found at [Google Internationalization on GitHub](https://github.com/googlei18n/libphonenumber/tree/master/java/libphonenumber/src/com/google/i18n/phonenumbers). – Magnus Oct 02 '18 at 22:17
4

According to the documentation:

Compare phone numbers a and b, and return true if they're identical enough for caller ID purposes.

The number is the same because the only difference is the prefix, which is not necessary for compare purposes.

luanjot
  • 1,176
  • 1
  • 7
  • 21
0

And if you really want to distinguish between a phone number and a phone number plus its a prefix you should string compare method.

String number1 = "+11234567890"; 
String number2 = "34567890"; 
number1.compareTo(number2);
pixel
  • 24,905
  • 36
  • 149
  • 251
FKSI
  • 148
  • 5