Getting telephone US local area code with Android
1- Add This Array to Strings.xml File
<string-array name="CountryCodes" >
<item>93,AF</item>
<item>355,AL</item>
<item>213,DZ</item>
<item>376,AD</item>
<item>244,AO</item>
<item>672,AQ</item>
<item>54,AR</item>
<item>374,AM</item>
<item>297,AW</item>
<item>61,AU</item>
<item>43,AT</item>
<item>994,AZ</item>
<item>973,BH</item>
<item>880,BD</item>
<item>375,BY</item>
<item>32,BE</item>
<item>501,BZ</item>
<item>229,BJ</item>
<item>975,BT</item>
<item>591,BO</item>
<item>387,BA</item>
<item>267,BW</item>
<item>55,BR</item>
<item>673,BN</item>
<item>359,BG</item>
<item>226,BF</item>
<item>95,MM</item>
<item>257,BI</item>
<item>855,KH</item>
<item>237,CM</item>
<item>1,CA</item>
<item>238,CV</item>
<item>236,CF</item>
<item>235,TD</item>
<item>56,CL</item>
<item>86,CN</item>
<item>61,CX</item>
<item>61,CC</item>
<item>57,CO</item>
<item>269,KM</item>
<item>242,CG</item>
<item>243,CD</item>
<item>682,CK</item>
<item>506,CR</item>
<item>385,HR</item>
<item>53,CU</item>
<item>357,CY</item>
<item>420,CZ</item>
<item>45,DK</item>
<item>253,DJ</item>
<item>670,TL</item>
<item>593,EC</item>
<item>20,EG</item>
<item>503,SV</item>
<item>240,GQ</item>
<item>291,ER</item>
<item>372,EE</item>
<item>251,ET</item>
<item>500,FK</item>
<item>298,FO</item>
<item>679,FJ</item>
<item>358,FI</item>
<item>33,FR</item>
<item>689,PF</item>
<item>241,GA</item>
<item>220,GM</item>
<item>995,GE</item>
<item>49,DE</item>
<item>233,GH</item>
<item>350,GI</item>
<item>30,GR</item>
<item>299,GL</item>
<item>502,GT</item>
<item>224,GN</item>
<item>245,GW</item>
<item>592,GY</item>
<item>509,HT</item>
<item>504,HN</item>
<item>852,HK</item>
<item>36,HU</item>
<item>91,IN</item>
<item>62,ID</item>
<item>98,IR</item>
<item>964,IQ</item>
<item>353,IE</item>
<item>44,IM</item>
<item>972,IL</item>
<item>39,IT</item>
<item>225,CI</item>
<item>81,JP</item>
<item>962,JO</item>
<item>7,KZ</item>
<item>254,KE</item>
<item>686,KI</item>
<item>965,KW</item>
<item>996,KG</item>
<item>856,LA</item>
<item>371,LV</item>
<item>961,LB</item>
<item>266,LS</item>
<item>231,LR</item>
<item>218,LY</item>
<item>423,LI</item>
<item>370,LT</item>
<item>352,LU</item>
<item>853,MO</item>
<item>389,MK</item>
<item>261,MG</item>
<item>265,MW</item>
<item>60,MY</item>
<item>960,MV</item>
<item>223,ML</item>
<item>356,MT</item>
<item>692,MH</item>
<item>222,MR</item>
<item>230,MU</item>
<item>262,YT</item>
<item>52,MX</item>
<item>691,FM</item>
<item>373,MD</item>
<item>377,MC</item>
<item>976,MN</item>
<item>382,ME</item>
<item>212,MA</item>
<item>258,MZ</item>
<item>264,NA</item>
<item>674,NR</item>
<item>977,NP</item>
<item>31,NL</item>
<item>599,AN</item>
<item>687,NC</item>
<item>64,NZ</item>
<item>505,NI</item>
<item>227,NE</item>
<item>234,NG</item>
<item>683,NU</item>
<item>850,KP</item>
<item>47,NO</item>
<item>968,OM</item>
<item>92,PK</item>
<item>680,PW</item>
<item>507,PA</item>
<item>675,PG</item>
<item>595,PY</item>
<item>51,PE</item>
<item>63,PH</item>
<item>870,PN</item>
<item>48,PL</item>
<item>351,PT</item>
<item>1,PR</item>
<item>974,QA</item>
<item>40,RO</item>
<item>7,RU</item>
<item>250,RW</item>
<item>590,BL</item>
<item>685,WS</item>
<item>378,SM</item>
<item>239,ST</item>
<item>966,SA</item>
<item>221,SN</item>
<item>381,RS</item>
<item>248,SC</item>
<item>232,SL</item>
<item>65,SG</item>
<item>421,SK</item>
<item>386,SI</item>
<item>677,SB</item>
<item>252,SO</item>
<item>27,ZA</item>
<item>82,KR</item>
<item>34,ES</item>
<item>94,LK</item>
<item>290,SH</item>
<item>508,PM</item>
<item>249,SD</item>
<item>597,SR</item>
<item>268,SZ</item>
<item>46,SE</item>
<item>41,CH</item>
<item>963,SY</item>
<item>886,TW</item>
<item>992,TJ</item>
<item>255,TZ</item>
<item>66,TH</item>
<item>228,TG</item>
<item>690,TK</item>
<item>676,TO</item>
<item>216,TN</item>
<item>90,TR</item>
<item>993,TM</item>
<item>688,TV</item>
<item>971,AE</item>
<item>256,UG</item>
<item>44,GB</item>
<item>380,UA</item>
<item>598,UY</item>
<item>1,US</item>
<item>998,UZ</item>
<item>678,VU</item>
<item>39,VA</item>
<item>58,VE</item>
<item>84,VN</item>
<item>681,WF</item>
<item>967,YE</item>
<item>260,ZM</item>
<item>263,ZW</item>
</string-array>
2-CopyThis Function To your Class
public String GetCountryZipCode(){
String CountryID="";
String CountryZipCode="";
TelephonyManager manager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
//getNetworkCountryIso
CountryID= manager.getSimCountryIso().toUpperCase();
String[] rl=this.getResources().getStringArray(R.array.CountryCodes);
for(int i=0;i<rl.length;i++){
String[] g=rl[i].split(",");
if(g[1].trim().equals(CountryID.trim())){
CountryZipCode=g[0];
break;
}
}
return CountryZipCode;
}
3-Call Function GetCountryZipCode()
4-write Thank you Wais.
Sorry to revive a dead thread, but I spent a while trying to solve this issue so hopefully my response will help someone else.
The example in the original question is confusing, you say you want to append the country code, but give New York area code 212 as an example; That is not a country code it is a local area code. The country code for USA is 1. So you would want the final number to look like "1-212-xxx-xxxx". My answer below explains how to determine the country code, not the local area code.
To get the country calling code for your own number, use getSimCountryIso(). Do not use getNetworkCountryIso(); getNetworkCountryIso will return the country that you are currently located in, but if you are travelling this will return the wrong country. For example if you are from Albania but are travelling in New York getSimCountryIso will return "al", but getNetworkCountryIso will return "us". Obviously if you use the country code for the USA, you have the wrong number.
Now you have a two character country code; for example Canada will be "ca". You can then use this as a lookup key for the table below (obtained from http://www.sikosoft.com/item/international_telephone_country_codes_in_xml_format_using_iso_639-1).
Since country codes don't ever change, it is acceptable to hard code a lookup table in your application. Unfortunately there doesn't seem to be a direct way to get the user's current country code.
<?xml version='1.0' encoding='UTF-8'?>
<icc>
<AF>93</AF>
<AL>355</AL>
<DZ>213</DZ>
<AD>376</AD>
<AO>244</AO>
<AQ>672</AQ>
<AR>54</AR>
<AM>374</AM>
<AW>297</AW>
<AU>61</AU>
<AT>43</AT>
<AZ>994</AZ>
<BH>973</BH>
<BD>880</BD>
<BY>375</BY>
<BE>32</BE>
<BZ>501</BZ>
<BJ>229</BJ>
<BT>975</BT>
<BO>591</BO>
<BA>387</BA>
<BW>267</BW>
<BR>55</BR>
<BN>673</BN>
<BG>359</BG>
<BF>226</BF>
<MM>95</MM>
<BI>257</BI>
<KH>855</KH>
<CM>237</CM>
<CA>1</CA>
<CV>238</CV>
<CF>236</CF>
<TD>235</TD>
<CL>56</CL>
<CN>86</CN>
<CX>61</CX>
<CC>61</CC>
<CO>57</CO>
<KM>269</KM>
<CG>242</CG>
<CD>243</CD>
<CK>682</CK>
<CR>506</CR>
<HR>385</HR>
<CU>53</CU>
<CY>357</CY>
<CZ>420</CZ>
<DK>45</DK>
<DJ>253</DJ>
<TL>670</TL>
<EC>593</EC>
<EG>20</EG>
<SV>503</SV>
<GQ>240</GQ>
<ER>291</ER>
<EE>372</EE>
<ET>251</ET>
<FK>500</FK>
<FO>298</FO>
<FJ>679</FJ>
<FI>358</FI>
<FR>33</FR>
<PF>689</PF>
<GA>241</GA>
<GM>220</GM>
<GE>995</GE>
<DE>49</DE>
<GH>233</GH>
<GI>350</GI>
<GR>30</GR>
<GL>299</GL>
<GT>502</GT>
<GN>224</GN>
<GW>245</GW>
<GY>592</GY>
<HT>509</HT>
<HN>504</HN>
<HK>852</HK>
<HU>36</HU>
<IN>91</IN>
<ID>62</ID>
<IR>98</IR>
<IQ>964</IQ>
<IE>353</IE>
<IM>44</IM>
<IL>972</IL>
<IT>39</IT>
<CI>225</CI>
<JP>81</JP>
<JO>962</JO>
<KZ>7</KZ>
<KE>254</KE>
<KI>686</KI>
<KW>965</KW>
<KG>996</KG>
<LA>856</LA>
<LV>371</LV>
<LB>961</LB>
<LS>266</LS>
<LR>231</LR>
<LY>218</LY>
<LI>423</LI>
<LT>370</LT>
<LU>352</LU>
<MO>853</MO>
<MK>389</MK>
<MG>261</MG>
<MW>265</MW>
<MY>60</MY>
<MV>960</MV>
<ML>223</ML>
<MT>356</MT>
<MH>692</MH>
<MR>222</MR>
<MU>230</MU>
<YT>262</YT>
<MX>52</MX>
<FM>691</FM>
<MD>373</MD>
<MC>377</MC>
<MN>976</MN>
<ME>382</ME>
<MA>212</MA>
<MZ>258</MZ>
<NA>264</NA>
<NR>674</NR>
<NP>977</NP>
<NL>31</NL>
<AN>599</AN>
<NC>687</NC>
<NZ>64</NZ>
<NI>505</NI>
<NE>227</NE>
<NG>234</NG>
<NU>683</NU>
<KP>850</KP>
<NO>47</NO>
<OM>968</OM>
<PK>92</PK>
<PW>680</PW>
<PA>507</PA>
<PG>675</PG>
<PY>595</PY>
<PE>51</PE>
<PH>63</PH>
<PN>870</PN>
<PL>48</PL>
<PT>351</PT>
<PR>1</PR>
<QA>974</QA>
<RO>40</RO>
<RU>7</RU>
<RW>250</RW>
<BL>590</BL>
<WS>685</WS>
<SM>378</SM>
<ST>239</ST>
<SA>966</SA>
<SN>221</SN>
<RS>381</RS>
<SC>248</SC>
<SL>232</SL>
<SG>65</SG>
<SK>421</SK>
<SI>386</SI>
<SB>677</SB>
<SO>252</SO>
<ZA>27</ZA>
<KR>82</KR>
<ES>34</ES>
<LK>94</LK>
<SH>290</SH>
<PM>508</PM>
<SD>249</SD>
<SR>597</SR>
<SZ>268</SZ>
<SE>46</SE>
<CH>41</CH>
<SY>963</SY>
<TW>886</TW>
<TJ>992</TJ>
<TZ>255</TZ>
<TH>66</TH>
<TG>228</TG>
<TK>690</TK>
<TO>676</TO>
<TN>216</TN>
<TR>90</TR>
<TM>993</TM>
<TV>688</TV>
<AE>971</AE>
<UG>256</UG>
<GB>44</GB>
<UA>380</UA>
<UY>598</UY>
<US>1</US>
<UZ>998</UZ>
<VU>678</VU>
<VA>39</VA>
<VE>58</VE>
<VN>84</VN>
<WF>681</WF>
<YE>967</YE>
<ZM>260</ZM>
<ZW>263</ZW>
</icc>
This question helped me so much, I want to give you all a class that provide country code from phone code and viceversa.
Usage:
-
CountryCodes.getCode(String country)
returns international code from country sign -
CountryCodes.getCountry(String code)
returns country signs from international code
An instance of this class can be provided as adapter to Views, for example in Activity onCreate:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout); // your layout xml
Spinner s = ( Spinner )findViewById( R.id.spinner1 ); // id of your spinner
CountryCodes cc = new CountryCodes( this );
s.setAdapter( cc );
TelephonyManager man = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
int index = CountryCodes.getIndex( man.getSimCountryIso() );
if( index > -1 )
{
s.setSelection( index );
}
}
What follows is the class code
CountryCodes.java
import java.util.ArrayList;
import java.util.Locale;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
/**
* Call getCountry( String code ) to get matching country sign.
* Call getCode( String country ) to get matching phone code.
* It has been extended from BaseAdapter in order to make it compatible with Spinner,
* ListView and so on (just instance it and give it as adapter).
*
* This class is provided AS IS without any warranty.
*
* @author Niki Romagnoli
*
*/
public class CountryCodes extends BaseAdapter{
private static final String[] m_Countries = {
"AD",
"AE",
"AF",
"AL",
"AM",
"AN",
"AO",
"AQ",
"AR",
"AT",
"AU",
"AW",
"AZ",
"BA",
"BD",
"BE",
"BF",
"BG",
"BH",
"BI",
"BJ",
"BL",
"BN",
"BO",
"BR",
"BT",
"BW",
"BY",
"BZ",
"CA",
"CC",
"CD",
"CF",
"CG",
"CH",
"CI",
"CK",
"CL",
"CM",
"CN",
"CO",
"CR",
"CU",
"CV",
"CX",
"CY",
"CZ",
"DE",
"DJ",
"DK",
"DZ",
"EC",
"EE",
"EG",
"ER",
"ES",
"ET",
"FI",
"FJ",
"FK",
"FM",
"FO",
"FR",
"GA",
"GB",
"GE",
"GH",
"GI",
"GL",
"GM",
"GN",
"GQ",
"GR",
"GT",
"GW",
"GY",
"HK",
"HN",
"HR",
"HT",
"HU",
"ID",
"IE",
"IL",
"IM",
"IN",
"IQ",
"IR",
"IT",
"JO",
"JP",
"KE",
"KG",
"KH",
"KI",
"KM",
"KP",
"KR",
"KW",
"KZ",
"LA",
"LB",
"LI",
"LK",
"LR",
"LS",
"LT",
"LU",
"LV",
"LY",
"MA",
"MC",
"MD",
"ME",
"MG",
"MH",
"MK",
"ML",
"MM",
"MN",
"MO",
"MR",
"MT",
"MU",
"MV",
"MW",
"MX",
"MY",
"MZ",
"NA",
"NC",
"NE",
"NG",
"NI",
"NL",
"NO",
"NP",
"NR",
"NU",
"NZ",
"OM",
"PA",
"PE",
"PF",
"PG",
"PH",
"PK",
"PL",
"PM",
"PN",
"PR",
"PT",
"PW",
"PY",
"QA",
"RO",
"RS",
"RU",
"RW",
"SA",
"SB",
"SC",
"SD",
"SE",
"SG",
"SH",
"SI",
"SK",
"SL",
"SM",
"SN",
"SO",
"SR",
"ST",
"SV",
"SY",
"SZ",
"TD",
"TG",
"TH",
"TJ",
"TK",
"TL",
"TM",
"TN",
"TO",
"TR",
"TV",
"TW",
"TZ",
"UA",
"UG",
"US",
"UY",
"UZ",
"VA",
"VE",
"VN",
"VU",
"WF",
"WS",
"YE",
"YT",
"ZA",
"ZM",
"ZW"
};
private static final String[] m_Codes = {
"376",
"971",
"93",
"355",
"374",
"599",
"244",
"672",
"54",
"43",
"61",
"297",
"994",
"387",
"880",
"32",
"226",
"359",
"973",
"257",
"229",
"590",
"673",
"591",
"55",
"975",
"267",
"375",
"501",
"1",
"61",
"243",
"236",
"242",
"41",
"225",
"682",
"56",
"237",
"86",
"57",
"506",
"53",
"238",
"61",
"357",
"420",
"49",
"253",
"45",
"213",
"593",
"372",
"20",
"291",
"34",
"251",
"358",
"679",
"500",
"691",
"298",
"33",
"241",
"44",
"995",
"233",
"350",
"299",
"220",
"224",
"240",
"30",
"502",
"245",
"592",
"852",
"504",
"385",
"509",
"36",
"62",
"353",
"972",
"44",
"91",
"964",
"98",
"39",
"962",
"81",
"254",
"996",
"855",
"686",
"269",
"850",
"82",
"965",
"7",
"856",
"961",
"423",
"94",
"231",
"266",
"370",
"352",
"371",
"218",
"212",
"377",
"373",
"382",
"261",
"692",
"389",
"223",
"95",
"976",
"853",
"222",
"356",
"230",
"960",
"265",
"52",
"60",
"258",
"264",
"687",
"227",
"234",
"505",
"31",
"47",
"977",
"674",
"683",
"64",
"968",
"507",
"51",
"689",
"675",
"63",
"92",
"48",
"508",
"870",
"1",
"351",
"680",
"595",
"974",
"40",
"381",
"7",
"250",
"966",
"677",
"248",
"249",
"46",
"65",
"290",
"386",
"421",
"232",
"378",
"221",
"252",
"597",
"239",
"503",
"963",
"268",
"235",
"228",
"66",
"992",
"690",
"670",
"993",
"216",
"676",
"90",
"688",
"886",
"255",
"380",
"256",
"1",
"598",
"998",
"39",
"58",
"84",
"678",
"681",
"685",
"967",
"262",
"27",
"260",
"263"
};
private Context m_Context;
public CountryCodes( Context cxt )
{
super();
m_Context = cxt;
}
/**
* Get phone code from country sign.
*
* @param country: two-chars country sign to fetch ("US", "IT", "GB", ...)
* @return string of matching phone code ("1", "39", "44", ...). null if none matches.
*/
public static String getCode( String country )
{
int index = getIndex( country );
return index == -1? null: getCode(index);
}
/**
* Get international code at provided index.
*
* @param index: array index
* @return international code
*/
public static String getCode( int index )
{
return m_Codes[index];
}
/**
* Get country signs from phone code.
* More countries may match the same code.
*
* @param code: phone code to fetch ("1", "39", "44", ...)
* @return list of uppercase country signs (["US","PR","CA"], ["IT","VA"], ["GB","IM"], ...)
* Empty list if none matches.
*/
public static ArrayList<String> getCountry( String code )
{
ArrayList<String> matches = new ArrayList<String>();
getCountry(code, matches);
return matches;
}
/**
* Memory cheap version of country fetching: uses user provided list as output which outside
* could be recycled on desire.
*
* @param code: country sign to fetch
* @param matches: list to fill with matches, used as output
*/
public static void getCountry( String code, ArrayList<String> matches )
{
matches.clear();
for( int i=0; i<m_Codes.length; ++i )
if( m_Codes[i].equals( code ) )
matches.add(getCountry(i));
}
/**
* Returns country sign at specified index of internal array.
*
* @param index: index to fetch
* @return country sign
*/
public static String getCountry( int index )
{
return m_Countries[index];
}
/**
* Looks for country sign array index.
*
* @param country: country sign to search
* @return array index. -1 if none matches.
*/
public static int getIndex( String country )
{
String search = country.toUpperCase(Locale.getDefault());
for( int i=0; i<m_Countries.length; ++i )
if( m_Countries[i].equals( search ) )
return i;
return -1;
}
@Override
public int getCount() {
return m_Codes.length;
}
@Override
public Object getItem(int index) {
return m_Countries[index];
}
@Override
public long getItemId(int index) {
return index;
}
@Override
public View getView(int index, View recycleView, ViewGroup viewGroup) {
TextView view;
if( recycleView == null )
{
view = new TextView(m_Context);
view.setPadding(30, 10, 10, 10);
}
else
{
view = (TextView)recycleView;
}
view.setText(m_Countries[index]);
return view;
}
}
I'm using it and seems to work but, you know, just death and taxes are certain. Feel free to customize it and suggest fixes.
HTH
Use compile 'com.googlecode.libphonenumber:libphonenumber:8.0.1'
dependency. This makes the task easy and provides accurate result because it's by google.
Here you can know more about it.
The output I m getting is something like this:
Here I m using spinner.
1) I have created a custom Adapter CountryCodesAdapter:
package com.amitupadhyay.getcountrycode;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.TextView;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
/**
* Created by aupadhyay on 1/24/17.
*/
public class CountryCodesAdapter extends BaseAdapter {
private final LayoutInflater mInflater;
private final List<CountryCode> mData;
private final int mViewId;
private final int mDropdownViewId;
private int mSelected;
public static final class CountryCode implements Comparable<String> {
public String regionCode;
public int countryCode;
public String regionName;
@Override
public int compareTo(String another) {
return regionCode != null && another != null ? regionCode.compareTo(another) : 1;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o != null && o instanceof CountryCode) {
CountryCode other = (CountryCode) o;
return regionCode != null &&
regionCode.equals(other.regionCode);
}
return false;
}
@Override
public String toString() {
return regionCode;
}
}
public CountryCodesAdapter(Context context, int viewId, int dropdownViewId) {
this(context, new ArrayList<CountryCode>(), viewId, dropdownViewId);
}
public CountryCodesAdapter(Context context, List<CountryCode> data, int viewId, int dropdownViewId) {
mInflater = LayoutInflater.from(context);
mData = data;
mViewId = viewId;
mDropdownViewId = dropdownViewId;
}
public void add(CountryCode entry) {
mData.add(entry);
}
public void add(String regionCode) {
CountryCode cc = new CountryCode();
cc.regionCode = regionCode;
cc.countryCode = PhoneNumberUtil.getInstance().getCountryCodeForRegion(regionCode);
cc.regionName = getRegionDisplayName(regionCode, Locale.getDefault());
mData.add(cc);
}
public void clear() {
mData.clear();
}
public void sort(Comparator<? super CountryCode> comparator) {
Collections.sort(mData, comparator);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
CountryCode e = mData.get(position);
return (e != null) ? e.countryCode : -1;
}
public int getPositionForId(CountryCode cc) {
return cc != null ? mData.indexOf(cc) : -1;
}
public void setSelected(int position) {
mSelected = position;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
CheckedTextView textView;
View view;
if (convertView == null) {
view = mInflater.inflate(mDropdownViewId, parent, false);
textView = (CheckedTextView) view.findViewById(android.R.id.text1);
view.setTag(textView);
}
else {
view = convertView;
textView = (CheckedTextView) view.getTag();
}
CountryCode e = mData.get(position);
StringBuilder text = new StringBuilder(5)
.append(e.regionName)
.append(" (+")
.append(e.countryCode)
.append(')');
textView.setText(text);
textView.setChecked((mSelected == position));
return view;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView;
View view;
if (convertView == null) {
view = mInflater.inflate(mViewId, parent, false);
textView = (TextView) view.findViewById(android.R.id.text1);
view.setTag(textView);
}
else {
view = convertView;
textView = (TextView) view.getTag();
}
CountryCode e = mData.get(position);
StringBuilder text = new StringBuilder(3)
.append('+')
.append(e.countryCode)
.append(" (")
.append(e.regionName)
.append(')');
textView.setText(text);
return view;
}
/** Returns the localized region name for the given region code. */
public String getRegionDisplayName(String regionCode, Locale language) {
return (regionCode == null || regionCode.equals("ZZ") ||
regionCode.equals(PhoneNumberUtil.REGION_CODE_FOR_NON_GEO_ENTITY))
? "" : new Locale("", regionCode).getDisplayCountry(language);
}
}
2) Now the layout of my Activity where I am displaying the spinner of country code is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<include layout="@layout/toolbar_simple"/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="18dip" >
<Spinner android:id="@+id/phone_cc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:spinnerMode="dialog"/>
<EditText
android:id="@+id/phone_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_validation_number"
android:inputType="phone" />
<Button
android:id="@+id/button_validate"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:text="@string/button_validate" />
</LinearLayout>
</ScrollView>
</LinearLayout>
3) java Activity code is below:
package com.amitupadhyay.getcountrycode;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import com.amitupadhyay.getcountrycode.CountryCodesAdapter.CountryCode;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
public class NumberValidation extends AppCompatActivity {
private Spinner mCountryCode;
private EditText mPhone;
private Button mValidateButton;
/**
* Compatibility method for {@link PhoneNumberUtil#getSupportedRegions()}.
* This was introduced because crappy Honeycomb has an old version of
* libphonenumber, therefore Dalvik will insist on we using it.
* In case getSupportedRegions doesn't exist, getSupportedCountries will be
* used.
*/
@SuppressWarnings("unchecked")
private Set<String> getSupportedRegions(PhoneNumberUtil util) {
try {
return (Set<String>) util.getClass()
.getMethod("getSupportedRegions")
.invoke(util);
}
catch (NoSuchMethodException e) {
try {
return (Set<String>) util.getClass()
.getMethod("getSupportedCountries")
.invoke(util);
}
catch (Exception helpme) {
// ignored
}
}
catch (Exception e) {
// ignored
}
return new HashSet<>();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.number_validation);
//setupToolbar(false);
mCountryCode = (Spinner) findViewById(R.id.phone_cc);
mPhone = (EditText) findViewById(R.id.phone_number);
mValidateButton = (Button) findViewById(R.id.button_validate);
// populate country codes
final CountryCodesAdapter ccList = new CountryCodesAdapter(this,
android.R.layout.simple_list_item_1,
android.R.layout.simple_spinner_dropdown_item);
PhoneNumberUtil util = PhoneNumberUtil.getInstance();
Set<String> ccSet = getSupportedRegions(util);
for (String cc : ccSet)
ccList.add(cc);
ccList.sort(new Comparator<CountryCodesAdapter.CountryCode>() {
public int compare(CountryCodesAdapter.CountryCode lhs, CountryCodesAdapter.CountryCode rhs) {
return lhs.regionName.compareTo(rhs.regionName);
}
});
mCountryCode.setAdapter(ccList);
mCountryCode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ccList.setSelected(position);
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
// FIXME this doesn't consider creation because of configuration change
Phonenumber.PhoneNumber myNum = getMyNumber(this);
if (myNum != null) {
CountryCode cc = new CountryCode();
cc.regionCode = util.getRegionCodeForNumber(myNum);
if (cc.regionCode == null)
cc.regionCode = util.getRegionCodeForCountryCode(myNum.getCountryCode());
mCountryCode.setSelection(ccList.getPositionForId(cc));
mPhone.setText(String.valueOf(myNum.getNationalNumber()));
}
else {
final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
final String regionCode = tm.getSimCountryIso().toUpperCase(Locale.US);
CountryCode cc = new CountryCode();
cc.regionCode = regionCode;
cc.countryCode = util.getCountryCodeForRegion(regionCode);
mCountryCode.setSelection(ccList.getPositionForId(cc));
}
}
/** Returns the (parsed) number stored in this device SIM card. */
@SuppressLint("HardwareIds")
public Phonenumber.PhoneNumber getMyNumber(Context context) {
try {
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final String regionCode = tm.getSimCountryIso().toUpperCase(Locale.US);
return PhoneNumberUtil.getInstance().parse(tm.getLine1Number(), regionCode);
}
catch (Exception e) {
return null;
}
}
}
Few extra features:
a) Your country will get automatically selected in the spinner.
To achieve I have used this:
Phonenumber.PhoneNumber myNum = getMyNumber(this);
if (myNum != null) {
CountryCode cc = new CountryCode();
cc.regionCode = util.getRegionCodeForNumber(myNum);
if (cc.regionCode == null)
cc.regionCode = util.getRegionCodeForCountryCode(myNum.getCountryCode());
mCountryCode.setSelection(ccList.getPositionForId(cc));
mPhone.setText(String.valueOf(myNum.getNationalNumber()));
}
else {
final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
final String regionCode = tm.getSimCountryIso().toUpperCase(Locale.US);
CountryCode cc = new CountryCode();
cc.regionCode = regionCode;
cc.countryCode = util.getCountryCodeForRegion(regionCode);
mCountryCode.setSelection(ccList.getPositionForId(cc));
}
I think this method is little better than other ways listed here. So I posted this. Hope someone may find it helpful :-)
This project on GitHub is here