Extract code country from phone number [libphonenumber] - android

I have a string like this : +33123456789 (french phone number). I want to extract the country code (+33) without knowing the country. For example, it should work if i have another phone from another country. I use the google library https://code.google.com/p/libphonenumber/.
If I know the country, it is cool I can find the country code :
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
int countryCode = phoneUtil.getCountryCodeForRegion(locale.getCountry());
but I don't find a way to parse a string without to know the country.

Okay, so I've joined the google group of libphonenumber ( https://groups.google.com/forum/?hl=en&fromgroups#!forum/libphonenumber-discuss ) and I've asked a question.
I don't need to set the country in parameter if my phone number begins with "+". Here is an example :
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
// phone must begin with '+'
PhoneNumber numberProto = phoneUtil.parse(phone, "");
int countryCode = numberProto.getCountryCode();
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}

I have got kept a handy helper method to take care of this based on one answer posted above:
Imports:
import com.google.i18n.phonenumbers.NumberParseException
import com.google.i18n.phonenumbers.PhoneNumberUtil
Function:
fun parseCountryCode( phoneNumberStr: String?): String {
val phoneUtil = PhoneNumberUtil.getInstance()
return try {
// phone must begin with '+'
val numberProto = phoneUtil.parse(phoneNumberStr, "")
numberProto.countryCode.toString()
} catch (e: NumberParseException) {
""
}
}

In here you can save the phone number as international formatted phone number
internationalFormatPhoneNumber = phoneUtil.format(givenPhoneNumber, PhoneNumberFormat.INTERNATIONAL);
it return the phone number as
International format +94 71 560 4888
so now I have get country code as this
String countryCode = internationalFormatPhoneNumber.substring(0,internationalFormatPhoneNumber.indexOf('')).replace('+', ' ').trim();
Hope this will help you

Here is a solution to get the country based on an international phone number without using the Google library.
Let me explain first why it is so difficult to figure out the country. The country code of few countries is 1 digit, 2, 3 or 4 digits. That would be simple enough. But the country code 1 is not just used for US, but also for Canada and some smaller places:
1339 USA
1340 Virgin Islands (Caribbean Islands)
1341 USA
1342 not used
1343 Canada
Digits 2..4 decide, if it is US or Canada or ... There is no easy way to figure out the country, like the first xxx are Canada, the rest US.
For my code, I defined a class which holds information for ever digit:
public class DigitInfo {
public char Digit;
public Country? Country;
public DigitInfo?[]? Digits;
}
A first array holds the DigitInfos for the first digit in the number. The second digit is used as an index into DigitInfo.Digits. One travels down that Digits chain, until Digits is empty. If Country is defined (i.e. not null) that value gets returned, otherwise any Country defined earlier gets returned:
country code 1: byPhone[1].Country is US
country code 1236: byPhone[1].Digits[2].Digits[3].Digits[6].Country is Canada
country code 1235: byPhone[1].Digits[2].Digits[3].Digits[5].Country is null. Since
byPhone[1].Country is US, also 1235 is US, because no other
country was found in the later digits
Here is the method which returns the country based on the phone number:
/// <summary>
/// Returns the Country based on an international dialing code.
/// </summary>
public static Country? GetCountry(ReadOnlySpan<char> phoneNumber) {
if (phoneNumber.Length==0) return null;
var isFirstDigit = true;
DigitInfo? digitInfo = null;
Country? country = null;
foreach (var digitChar in phoneNumber) {
var digitIndex = digitChar - '0';
if (isFirstDigit) {
isFirstDigit = false;
digitInfo = ByPhone[digitIndex];
} else {
if (digitInfo!.Digits is null) return country;
digitInfo = digitInfo.Digits[digitIndex];
}
if (digitInfo is null) return country;
country = digitInfo.Country??country;
}
return country;
}
The rest of the code (digitInfos for every country of the world, test code, ...) is too big to be posted here, but it can be found on Github:
https://github.com/PeterHuberSg/WpfWindowsLib/blob/master/WpfWindowsHelperLib/CountryCode.cs
The code is part of a WPF TextBox and the library contains also other controls for email addresses, etc. A more detailed description is on CodeProject: International Phone Number Validation Explained in Detail
Change 23.1.23: I moved CountryCode.cs to WpfWindowsHelperLib, which doesn't have any WPF dependencies, despite it's name.

Use a try catch block like below:
try {
const phoneNumber = this.phoneUtil.parseAndKeepRawInput(value, this.countryCode);
}catch(e){}

If the string containing the phone number will always start this way (+33 or another country code) you should use regex to parse and get the country code and then use the library to get the country associated to the number.

Here's a an answer how to find country calling code without using third-party libraries (as real developer does):
Get list of all available country codes, Wikipedia can help here:
https://en.wikipedia.org/wiki/List_of_country_calling_codes
Parse data in a tree structure where each digit is a branch.
Traverse your tree digit by digit until you are at the last branch - that's your country code.

Related

String.format with English local but numbers are arabic

I am calculating priceAfterDsicount then place value in EditText(so user can modify it after App calculation)
Value retured from format is arabic numbers
this is code
private fun handleDiscount() {
val price = edPackagePrice.text.toString().toDoubleOrNull()
val discount = discount_percentage_edit_text.text.toString().toIntOrNull()
"handleDiscount before price$price discount$discount".log(mTag)
price?.let {
discount?.let {
val finalValue = String.format("%.1f", ValuesHelper.getPercentage(price, discount),Locale.US)
price_after_discount_edit_text.setText(finalValue)
"handleDiscount ook price$price discount$discount, final $finalValue".log(mTag)
}
}
if (discount == null) {
"handleDiscount $price , ${edPackagePrice.text}".log(mTag)
price_after_discount_edit_text.setText("")
price?.let { price_after_discount_edit_text.setText(price.toString()) }
}
"handleDiscount after price_after_discount_edit_text${price_after_discount_edit_text.text.toString()} ".log(mTag)
}
Output at Run
so what is problem?
NOTE
App language is arabic(user can change it from app).
I found other way to convert arabic number to english
Use Java.math.BigDecimal ,it will automatically construct English numeric equivalent to Arabic numeric equivalent , After you have English numeric equivalent do your calculation and when you want to update the UI after calculation use the device locale to show the end result to user in Arabic , BigDecimal only work with digits i.e. 0123. For special characters like , you have to do exception handling , we have .isDigit() method of Character class that you can leverage to iterate over whole input string and remove , before doing calculation,hope this helps.

Android Get Country Emoji Flag Using Locale

I have seen that since Lollipop, Android has built in Emoji flags for different countries. Is it possible to use the devices locale to retrieve the Emoji flag for that country?
I wanted to insert the Emoji flag into a TextView which contains the user's location.
Emoji is a Unicode symbols. Based on the Unicode character table Emoji flags consist of 26 alphabetic Unicode characters (A-Z) intended to be used to encode ISO 3166-1 alpha-2 two-letter country codes (wiki).
That means it is possible to split two-letter country code and convert each A-Z letter to regional indicator symbol letter:
private String localeToEmoji(Locale locale) {
String countryCode = locale.getCountry();
int firstLetter = Character.codePointAt(countryCode, 0) - 0x41 + 0x1F1E6;
int secondLetter = Character.codePointAt(countryCode, 1) - 0x41 + 0x1F1E6;
return new String(Character.toChars(firstLetter)) + new String(Character.toChars(secondLetter));
}
Or in Kotlin, for example (assuming UTF-8):
val Locale.flagEmoji: String
get() {
val firstLetter = Character.codePointAt(country, 0) - 0x41 + 0x1F1E6
val secondLetter = Character.codePointAt(country, 1) - 0x41 + 0x1F1E6
return String(Character.toChars(firstLetter)) + String(Character.toChars(secondLetter))
}
Where 0x41 represents uppercase A letter and 0x1F1E6 is REGIONAL INDICATOR SYMBOL LETTER A in the Unicode table.
Note: This code example is simplified and doesn't have required checks related to country code, that could be not available inside the locale.
Based on this answer, I wrote a Kotlin version below using extension function.
I also added some checks to handle unknown country code.
/**
* This method is to change the country code like "us" into 🇺🇸
* Stolen from https://stackoverflow.com/a/35849652/75579
* 1. It first checks if the string consists of only 2 characters: ISO 3166-1 alpha-2 two-letter country codes (https://en.wikipedia.org/wiki/Regional_Indicator_Symbol).
* 2. It then checks if both characters are alphabet
* do nothing if it doesn't fulfil the 2 checks
* caveat: if you enter an invalid 2 letter country code, say "XX", it will pass the 2 checks, and it will return unknown result
*/
fun String.toFlagEmoji(): String {
// 1. It first checks if the string consists of only 2 characters: ISO 3166-1 alpha-2 two-letter country codes (https://en.wikipedia.org/wiki/Regional_Indicator_Symbol).
if (this.length != 2) {
return this
}
val countryCodeCaps = this.toUpperCase() // upper case is important because we are calculating offset
val firstLetter = Character.codePointAt(countryCodeCaps, 0) - 0x41 + 0x1F1E6
val secondLetter = Character.codePointAt(countryCodeCaps, 1) - 0x41 + 0x1F1E6
// 2. It then checks if both characters are alphabet
if (!countryCodeCaps[0].isLetter() || !countryCodeCaps[1].isLetter()) {
return this
}
return String(Character.toChars(firstLetter)) + String(Character.toChars(secondLetter))
}
Runnable Code Snippet
I also included a runnable Kotlin snippet using Kotlin Playground. In order to run the snippet you need to:
click "Show code snippet"
click "Run Code Snippet"
click the play button at the right top of the generated console
scroll to the bottom to see the result (it's hidden..)
<script src="https://unpkg.com/kotlin-playground#1.6.0/dist/playground.min.js" data-selector=".code"></script>
<div class="code" style="display:none;">
/**
* This method is to change the country code like "us" into 🇺🇸
* Stolen from https://stackoverflow.com/a/35849652/75579
* 1. It first checks if the string consists of only 2 characters: ISO 3166-1 alpha-2 two-letter country codes (https://en.wikipedia.org/wiki/Regional_Indicator_Symbol).
* 2. It then checks if both characters are alphabet
* do nothing if it doesn't fulfil the 2 checks
* caveat: if you enter an invalid 2 letter country code, say "XX", it will pass the 2 checks, and it will return unknown result
*/
fun String.toFlagEmoji(): String {
// 1. It first checks if the string consists of only 2 characters: ISO 3166-1 alpha-2 two-letter country codes (https://en.wikipedia.org/wiki/Regional_Indicator_Symbol).
if (this.length != 2) {
return this
}
val countryCodeCaps = this.toUpperCase() // upper case is important because we are calculating offset
val firstLetter = Character.codePointAt(countryCodeCaps, 0) - 0x41 + 0x1F1E6
val secondLetter = Character.codePointAt(countryCodeCaps, 1) - 0x41 + 0x1F1E6
// 2. It then checks if both characters are alphabet
if (!countryCodeCaps[0].isLetter() || !countryCodeCaps[1].isLetter()) {
return this
}
return String(Character.toChars(firstLetter)) + String(Character.toChars(secondLetter))
}
fun main(args: Array<String>){
println("us".toFlagEmoji())
println("AF".toFlagEmoji())
println("BR".toFlagEmoji())
println("MY".toFlagEmoji())
println("JP".toFlagEmoji())
}
</div>
When I first wrote this answer I somehow overlooked that I've only worked on Android via React Native!
Anyway, here's my JavaScript solution that works with or without ES6 support.
function countryCodeToFlagEmoji(country) {
return typeof String.fromCodePoint === "function"
? String.fromCodePoint(...[...country].map(c => c.charCodeAt() + 0x1f185))
: [...country]
.map(c => "\ud83c" + String.fromCharCode(0xdd85 + c.charCodeAt()))
.join("");
}
console.log(countryCodeToFlagEmoji("au"));
console.log(countryCodeToFlagEmoji("aubdusca"));
If you want to pass in the country codes as capital letters instead, just change the two offsets to 0x1f1a5 and 0xdda5.
You can get the country code very simple.
I want to talk about flag selection according to country code.
I wrote a class about it and it is very simple to use.
usage:
String countryWithFlag = CountryFlags.getCountryFlagByCountryCode("TR") + " " + "Türkiye";
Output : 🇹🇷 Türkiye
You can use it with Android TextView too :)
You can check out the class here
It works very well on Android 6 and above.
I am using this so easily.
Get the Unicode from here.
For Bangladesh flag it is U+1F1E7 U+1F1E9
Now,
{...
String flag = getEmojiByUnicode(0x1F1E7)+getEmojiByUnicode(0x1F1E9)+ " Bangladesh";
}
public String getEmojiByUnicode(int unicode){
return new String(Character.toChars(unicode));
}
It will show > (Bangladeshi flag) Bangladesh
I was looking for that too but I don't think it's possible yet.
Have a look here:
http://developer.android.com/reference/java/util/Locale.html
No mentioning about flags.
_
Alternately you can check the answer here:
Android Countries list with flags and availability of getting iso mobile codes
that might help you.

How to get country code from mobile number using libphonenumber api in Android [duplicate]

This question already has answers here:
Extract code country from phone number [libphonenumber]
(7 answers)
Closed 5 years ago.
I am using libphonenumber api https://code.google.com/p/libphonenumber/ in android project, I am getting country code using following code
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber numberProto = phoneUtil.parse(number, "IN");
int countryCode = numberProto.getCountryCode();
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
My question is:-
-- I have number like +447870000000 but don't know about country code but want to get country code from this number like +44 how can I get it through this api ?
please help me
Thanks in advance
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.service_activity);
/*********** read indicative sim *************/
TelephonyManager telMgr = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String simContryiso = telMgr.getSimCountryIso();
String indicative = Iso2Phone.getPhone(simContryiso);
}
//create a class which contains the indicative of all the country and the ISO code
public class Iso2Phone
{
// Get the indicative
public static String getPhone(String code)
{
return country_to_indicative.get(code.toUpperCase());
}
private static Map<String, String> country_to_indicative = new HashMap<String, String>();
static
{
country_to_indicative.put("AF", "+93");
country_to_indicative.put("AL", "+355");
country_to_indicative.put("DZ", "+213");
country_to_indicative.put("AS", "+1684");
country_to_indicative.put("AD", "+376");
country_to_indicative.put("AO", "+244");
country_to_indicative.put("AI", "+1264");
country_to_indicative.put("AG", "+1268");
country_to_indicative.put("AR", "+54");
country_to_indicative.put("AM", "+374");
country_to_indicative.put("AU", "+61");
country_to_indicative.put("AW", "+297");
country_to_indicative.put("AT", "+43");
country_to_indicative.put("AZ", "+994");
country_to_indicative.put("BS", "+1242");
country_to_indicative.put("BH", "+973");
country_to_indicative.put("BD", "+880");
country_to_indicative.put("BB", "+1246");
country_to_indicative.put("BY", "+375");
country_to_indicative.put("BE", "+32");
country_to_indicative.put("BZ", "+501");
country_to_indicative.put("BJ", "+229");
country_to_indicative.put("BM", "+1441");
country_to_indicative.put("BT", "+975");
country_to_indicative.put("BO", "+591");
country_to_indicative.put("BA", "+387");
country_to_indicative.put("BW", "+267");
country_to_indicative.put("BR", "+55");
country_to_indicative.put("BN", "+673");
country_to_indicative.put("BG", "+359");
country_to_indicative.put("BF", "+226");
country_to_indicative.put("BI", "+257");
country_to_indicative.put("KH", "+855");
country_to_indicative.put("CM", "+237");
country_to_indicative.put("CA", "+1");
country_to_indicative.put("CV", "+238");
country_to_indicative.put("CF", "+236");
country_to_indicative.put("TD", "+235");
country_to_indicative.put("CL", "+56");
country_to_indicative.put("CN", "+86");
country_to_indicative.put("CO", "+57");
country_to_indicative.put("KM", "+269");
country_to_indicative.put("CD", "+243");
country_to_indicative.put("CG", "+242");
country_to_indicative.put("CR", "+506");
country_to_indicative.put("CI", "+225");
country_to_indicative.put("HR", "+385");
country_to_indicative.put("CU", "+53");
country_to_indicative.put("CY", "+357");
country_to_indicative.put("CZ", "+420");
country_to_indicative.put("DK", "+45");
country_to_indicative.put("DJ", "+253");
country_to_indicative.put("DM", "+1767");
country_to_indicative.put("DO", "+1829");
country_to_indicative.put("EC", "+593");
country_to_indicative.put("EG", "+20");
country_to_indicative.put("SV", "+503");
country_to_indicative.put("GQ", "+240");
country_to_indicative.put("ER", "+291");
country_to_indicative.put("EE", "+372");
country_to_indicative.put("ET", "+251");
country_to_indicative.put("FJ", "+679");
country_to_indicative.put("FI", "+358");
country_to_indicative.put("FR", "+33");
country_to_indicative.put("GA", "+241");
country_to_indicative.put("GM", "+220");
country_to_indicative.put("GE", "+995");
country_to_indicative.put("DE", "+49");
country_to_indicative.put("GH", "+233");
country_to_indicative.put("GR", "+30");
country_to_indicative.put("GD", "+1473");
country_to_indicative.put("GT", "+502");
country_to_indicative.put("GN", "+224");
country_to_indicative.put("GW", "+245");
country_to_indicative.put("GY", "+592");
country_to_indicative.put("HT", "+509");
country_to_indicative.put("HN", "+504");
country_to_indicative.put("HU", "+36");
country_to_indicative.put("IS", "+354");
country_to_indicative.put("IN", "+91");
country_to_indicative.put("ID", "+62");
country_to_indicative.put("IR", "+98");
country_to_indicative.put("IQ", "+964");
country_to_indicative.put("IE", "+353");
country_to_indicative.put("IL", "+972");
country_to_indicative.put("IT", "+39");
country_to_indicative.put("JM", "+1876");
country_to_indicative.put("JP", "+81");
country_to_indicative.put("JO", "+962");
country_to_indicative.put("KZ", "+7");
country_to_indicative.put("KE", "+254");
country_to_indicative.put("KI", "+686");
country_to_indicative.put("KP", "+850");
country_to_indicative.put("KR", "+82");
country_to_indicative.put("KW", "+965");
country_to_indicative.put("KG", "+996");
country_to_indicative.put("LA", "+856");
country_to_indicative.put("LV", "+371");
country_to_indicative.put("LB", "+961");
country_to_indicative.put("LS", "+266");
country_to_indicative.put("LR", "+231");
country_to_indicative.put("LY", "+218");
country_to_indicative.put("LI", "+423");
country_to_indicative.put("LT", "+370");
country_to_indicative.put("LU", "+352");
country_to_indicative.put("MK", "+389");
country_to_indicative.put("MG", "+261");
country_to_indicative.put("MW", "+265");
country_to_indicative.put("MY", "+60");
country_to_indicative.put("MV", "+960");
country_to_indicative.put("ML", "+223");
country_to_indicative.put("MT", "+356");
country_to_indicative.put("MH", "+692");
country_to_indicative.put("MR", "+222");
country_to_indicative.put("MU", "+230");
country_to_indicative.put("MX", "+52");
country_to_indicative.put("FM", "+691");
country_to_indicative.put("MD", "+373");
country_to_indicative.put("MC", "+377");
country_to_indicative.put("MN", "+976");
country_to_indicative.put("ME", "+382");
country_to_indicative.put("MA", "+212");
country_to_indicative.put("MZ", "+258");
country_to_indicative.put("MM", "+95");
country_to_indicative.put("NA", "+264");
country_to_indicative.put("NR", "+674");
country_to_indicative.put("NP", "+977");
country_to_indicative.put("NL", "+31");
country_to_indicative.put("NZ", "+64");
country_to_indicative.put("NI", "+505");
country_to_indicative.put("NE", "+227");
country_to_indicative.put("NG", "+234");
country_to_indicative.put("NO", "+47");
country_to_indicative.put("OM", "+968");
country_to_indicative.put("PK", "+92");
country_to_indicative.put("PW", "+680");
country_to_indicative.put("PA", "+507");
country_to_indicative.put("PG", "+675");
country_to_indicative.put("PY", "+595");
country_to_indicative.put("PE", "+51");
country_to_indicative.put("PH", "+63");
country_to_indicative.put("PL", "+48");
country_to_indicative.put("PT", "+351");
country_to_indicative.put("QA", "+974");
country_to_indicative.put("RO", "+40");
country_to_indicative.put("RU", "+7");
country_to_indicative.put("RW", "+250");
country_to_indicative.put("KN", "+1869");
country_to_indicative.put("LC", "+1758");
country_to_indicative.put("VC", "+1784");
country_to_indicative.put("WS", "+685");
country_to_indicative.put("SM", "+378");
country_to_indicative.put("ST", "+239");
country_to_indicative.put("SA", "+966");
country_to_indicative.put("SN", "+221");
country_to_indicative.put("RS", "+381");
country_to_indicative.put("SC", "+248");
country_to_indicative.put("SL", "+232");
country_to_indicative.put("SG", "+65");
country_to_indicative.put("SK", "+421");
country_to_indicative.put("SI", "+386");
country_to_indicative.put("SB", "+677");
country_to_indicative.put("SO", "+252");
country_to_indicative.put("ZA", "+27");
country_to_indicative.put("ES", "+34");
country_to_indicative.put("LK", "+94");
country_to_indicative.put("SD", "+249");
country_to_indicative.put("SR", "+597");
country_to_indicative.put("SZ", "+268");
country_to_indicative.put("SE", "+46");
country_to_indicative.put("CH", "+41");
country_to_indicative.put("SY", "+963");
country_to_indicative.put("TJ", "+992");
country_to_indicative.put("TZ", "+255");
country_to_indicative.put("TH", "+66");
country_to_indicative.put("TL", "+670");
country_to_indicative.put("TG", "+228");
country_to_indicative.put("TO", "+676");
country_to_indicative.put("TT", "+1868");
country_to_indicative.put("TN", "+216");
country_to_indicative.put("TR", "+90");
country_to_indicative.put("TM", "+993");
country_to_indicative.put("TV", "+688");
country_to_indicative.put("UG", "+256");
country_to_indicative.put("UA", "+380");
country_to_indicative.put("AE", "+971");
country_to_indicative.put("GB", "+44");
country_to_indicative.put("US", "+1");
country_to_indicative.put("UY", "+598");
country_to_indicative.put("UZ", "+998");
country_to_indicative.put("VU", "+678");
country_to_indicative.put("VA", "+39");
country_to_indicative.put("VE", "+58");
country_to_indicative.put("VN", "+84");
country_to_indicative.put("YE", "+967");
country_to_indicative.put("ZM", "+260");
country_to_indicative.put("ZW", "+263");
country_to_indicative.put("GE", "+995");
country_to_indicative.put("TW", "+886");
country_to_indicative.put("AZ", "+994");
country_to_indicative.put("MD", "+373");
country_to_indicative.put("SO", "+252");
country_to_indicative.put("GE", "+995");
country_to_indicative.put("AU", "+61");
country_to_indicative.put("CX", "+61");
country_to_indicative.put("CC", "+61");
country_to_indicative.put("NF", "+672");
country_to_indicative.put("NC", "+687");
country_to_indicative.put("PF", "+689");
country_to_indicative.put("YT", "+262");
country_to_indicative.put("GP", "+590");
country_to_indicative.put("GP", "+590");
country_to_indicative.put("PM", "+508");
country_to_indicative.put("WF", "+681");
country_to_indicative.put("PF", "+689");
country_to_indicative.put("CK", "+682");
country_to_indicative.put("NU", "+683");
country_to_indicative.put("TK", "+690");
country_to_indicative.put("GG", "+44");
country_to_indicative.put("IM", "+44");
country_to_indicative.put("JE", "+44");
country_to_indicative.put("AI", "+1264");
country_to_indicative.put("BM", "+1441");
country_to_indicative.put("IO", "+246");
country_to_indicative.put("VG", "+1284");
country_to_indicative.put("KY", "+1345");
country_to_indicative.put("FK", "+500");
country_to_indicative.put("GI", "+350");
country_to_indicative.put("MS", "+1664");
country_to_indicative.put("PN", "+870");
country_to_indicative.put("SH", "+290");
country_to_indicative.put("TC", "+1649");
country_to_indicative.put("MP", "+1670");
country_to_indicative.put("PR", "+1");
country_to_indicative.put("AS", "+1684");
country_to_indicative.put("GU", "+1671");
country_to_indicative.put("VI", "+1340");
country_to_indicative.put("HK", "+852");
country_to_indicative.put("MO", "+853");
country_to_indicative.put("FO", "+298");
country_to_indicative.put("GL", "+299");
country_to_indicative.put("GF", "+594");
country_to_indicative.put("GP", "+590");
country_to_indicative.put("MQ", "+596");
country_to_indicative.put("RE", "+262");
country_to_indicative.put("AX", "+35818");
country_to_indicative.put("AW", "+297");
country_to_indicative.put("AN", "+599");
country_to_indicative.put("SJ", "+47");
country_to_indicative.put("AC", "+247");
country_to_indicative.put("TA", "+290");
country_to_indicative.put("AQ", "+6721");
country_to_indicative.put("CS", "+381");
country_to_indicative.put("PS", "+970");
country_to_indicative.put("EH", "+212");
}
}
A nice Library has been provided
https://github.com/hbb20/CountryCodePickerProject
In dependency add
dependencies {
implementation 'com.hbb20:ccp:2.2.0'
}
then use this xml code
<com.hbb20.CountryCodePicker
android:id="#+id/ccp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fbutton:ccp_contentColor="#color/appcolor"
fbutton:ccp_textSize="#dimen/_10sdp" />
It will automatically populate the list of country code and also u can search in it.
If you have a number in a E164 format (in your case +447870000000) and you specify country code ISO in the parser, it will actually ignore the given iso code and do the formatting based on the number.
Country code ISO is needed when the number you give to the method is in national format.
As far as your code snippet goes, it should work.

How to determine if two phone numbers are the same?

If we have a phone number like 358541321 without a country code, sometimes when phone rings it says (+56 - 358541321) or +56358541321.
How to detect whether the ringed number is first number?
The number is not saved in phone memory in order to phone lookup.
https://developer.android.com/reference/android/telephony/PhoneNumberUtils.html
provides a neat solution:
import android.telephony.PhoneNumberUtils;
...
String one = "+51 - 3245678";
String two = "+513245678";
boolean isSame = PhoneNumberUtils.compare(one, two);
The usual solution to this problem is just to compare the last X (e.g. 7 or 8, depending on your country) digits of the number. In rare cases, this can lead to false positives, but usually it's a good approximation and it avoids the problem of different or missing country or area codes.
Java regular expression and String function replaceAll can do this easily.
this way,
String one = "+51 - 3245678";
String two = "+513245678";
one = one.replaceAll("[^0-9]","");
two = two.replaceAll("[^0-9]","");
Toast.makeText(this, one+" -- "+two, Toast.LENGTH_LONG).show();
if(one.equalsIgnoreCase(two))
{
Toast.makeText(this, "Both Are Equal", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "Different", Toast.LENGTH_LONG).show();
}

Get phone number without country code for the purpose of comparing numbers

I can obtain the phone number from an incoming call or from a sms message. unfortunately, in case of the SMS there might be the country code in it. So, basically I need to obtain the plain phone number, without country code, in order to compare it with existing numbers in Contacts.
If you want to compare phone numbers you can always use the
PhoneNumberUtils.compare(number1, number2);
or
PhoneNumberUtils.compare(context, number1, number2);
Then you don't have to worry about the country code, it will just compare the numbers from the reversed order and see if they match (enough for callerID purposes at least).
fast untested approach (AFAIK phone numbers have 10 digits):
// As I said, AFAIK phone numbers have 10 digits... (at least here in Mexico this is true)
int digits = 10;
// the char + is always at first.
int plus_sign_pos = 0;
// Always send the number to this function to remove the first n digits (+1,+52, +520, etc)
private String removeCountryCode(String number) {
if (hasCountryCode(number)) {
// +52 for MEX +526441122345, 13-10 = 3, so we need to remove 3 characters
int country_digits = number.length() - digits;
number = number.substring(country_digits);
}
return number;
}
// Every country code starts with + right?
private boolean hasCountryCode(String number) {
return number.charAt(plus_sign_pos) == '+'; // Didn't String had contains() method?...
}
then you just call these functions

Categories

Resources