Getting telephone US local area code with Android - telephonymanager

I would like to know how can i get the device/user area code from within my android app
I know there is a lib named TelephonyManager but i couldn't find the country code feature
To make myself clear:
I have an activity which asks the user to enter his phone number and i want the area code to be taken from the device (from his carrier?)
If i would open my app in new york i would get +212 as the code and a text box to enter my own number

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

in this case this would look like:
/**
* network iso code: referred and listed at:
* http://en.wikipedia.org/wiki/List_of_mobile_country_codes
*/
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
Constants.DEVICE_COUNTRY = manager.getNetworkCountryIso();
So nobody has to look and double-check (context is a local variable of a valid Context object).
Constants.DEVICE_COUNTRY is of Type String :) (just a variable)

add these to the string.xml
Enjoy:)
<string-array name="country_code">
<item></item>
<item>
+93
</item>
<item>
+355
</item>
<item>
+213
</item>
<item>
+1684
</item>
<item>
+376
</item>
<item>
+244
</item>
<item>
+1264
</item>
<item>
+672
</item>
<item>
+1268
</item>
<item>
+54
</item>
<item>
+374
</item>
<item>
+297
</item>
<item>
+61
</item>
<item>
+43
</item>
<item>
+994
</item>
<item>
+1242
</item>
<item>
+973
</item>
<item>
+880
</item>
<item>
+1246
</item>
<item>
+375
</item>
<item>
+32
</item>
<item>
+501
</item>
<item>
+229
</item>
<item>
+1441
</item>
<item>
+975
</item>
<item>
+591
</item>
<item>
+387
</item>
<item>
+267
</item>
<item>
+55
</item>
<item>
+246
</item>
<item>
+1284
</item>
<item>
+673
</item>
<item>
+359
</item>
<item>
+226
</item>
<item>
+257
</item>
<item>
+855
</item>
<item>
+237
</item>
<item>
+1
</item>
<item>
+238
</item>
<item>
+1345
</item>
<item>
+236
</item>
<item>
+235
</item>
<item>
+56
</item>
<item>
+86
</item>
<item>
+61
</item>
<item>
+61
</item>
<item>
+57
</item>
<item>
+269
</item>
<item>
+682
</item>
<item>
+506
</item>
<item>
+385
</item>
<item>
+53
</item>
<item>
+599
</item>
<item>
+357
</item>
<item>
+420
</item>
<item>
+243
</item>
<item>
+45
</item>
<item>
+253
</item>
<item>
+1767
</item>
<item>
+1809
</item>
<item>
+670
</item>
<item>
+593
</item>
<item>
+20
</item>
<item>
+503
</item>
<item>
+240
</item>
<item>
+291
</item>
<item>
+372
</item>
<item>
+251
</item>
<item>
+500
</item>
<item>
+298
</item>
<item>
+679
</item>
<item>
+358
</item>
<item>
+33
</item>
<item>
+689
</item>
<item>
+241
</item>
<item>
+220
</item>
<item>
+995
</item>
<item>
+49
</item>
<item>
+233
</item>
<item>
+350
</item>
<item>
+30
</item>
<item>
+299
</item>
<item>
+1473
</item>
<item>
+1671
</item>
<item>
+502
</item>
<item>
+441481
</item>
<item>
+224
</item>
<item>
+245
</item>
<item>
+592
</item>
<item>
+509
</item>
<item>
+504
</item>
<item>
+852
</item>
<item>
+36
</item>
<item>
+354
</item>
<item>
+91
</item>
<item>
+62
</item>
<item>
+98
</item>
<item>
+964
</item>
<item>
+53
</item>
<item>
+441624
</item>
<item>
+972
</item>
<item>
+39
</item>
<item>
+225
</item>
<item>
+1876
</item>
<item>
+81
</item>
<item>
+441534
</item>
<item>
+962
</item>
<item>
+7
</item>
<item>
+254
</item>
<item>
+686
</item>
<item>
+383
</item>
<item>
+965
</item>
<item>
+996
</item>
<item>
+856
</item>
<item>
+371
</item>
<item>
+961
</item>
<item>
+266
</item>
<item>
+231
</item>
<item>
+218
</item>
<item>
+423
</item>
<item>
+370
</item>
<item>
+352
</item>
<item>
+853
</item>
<item>
+389
</item>
<item>
+261
</item>
<item>
+265
</item>
<item>
+60
</item>
<item>
+960
</item>
<item>
+223
</item>
<item>
+356
</item>
<item>
+692
</item>
<item>
+222
</item>
<item>
+230
</item>
<item>
+262
</item>
<item>
+52
</item>
<item>
+691
</item>
<item>
+373
</item>
<item>
+377
</item>
<item>
+976
</item>
<item>
+382
</item>
<item>
+1664
</item>
<item>
+212
</item>
<item>
+258
</item>
<item>
+95
</item>
<item>
+264
</item>
<item>
+674
</item>
<item>
+977
</item>
<item>
+31
</item>
<item>
+599
</item>
<item>
+687
</item>
<item>
+64
</item>
<item>
+505
</item>
<item>
+227
</item>
<item>
+234
</item>
<item>
+683
</item>
<item>
+850
</item>
<item>
+1670
</item>
<item>
+47
</item>
<item>
+968
</item>
<item>
+92
</item>
<item>
+680
</item>
<item>
+970
</item>
<item>
+507
</item>
<item>
+675
</item>
<item>
+595
</item>
<item>
+51
</item>
<item>
+63
</item>
<item>
+64
</item>
<item>
+48
</item>
<item>
+351
</item>
<item>
+1787
</item>
<item>
+974
</item>
<item>
+242
</item>
<item>
+262
</item>
<item>
+40
</item>
<item>
+7
</item>
<item>
+250
</item>
<item>
+590
</item>
<item>
+290
</item>
<item>
+1869
</item>
<item>
+1758
</item>
<item>
+590
</item>
<item>
+508
</item>
<item>
+1784
</item>
<item>
+685
</item>
<item>
+378
</item>
<item>
+239
</item>
<item>
+966
</item>
<item>
+221
</item>
<item>
+381
</item>
<item>
+248
</item>
<item>
+232
</item>
<item>
+65
</item>
<item>
+1721
</item>
<item>
+421
</item>
<item>
+386
</item>
<item>
+677
</item>
<item>
+252
</item>
<item>
+27
</item>
<item>
+82
</item>
<item>
+211
</item>
<item>
+34
</item>
<item>
+94
</item>
<item>
+249
</item>
<item>
+597
</item>
<item>
+47
</item>
<item>
+268
</item>
<item>
+46
</item>
<item>
+41
</item>
<item>
+963
</item>
<item>
+886
</item>
<item>
+992
</item>
<item>
+255
</item>
<item>
+66
</item>
<item>
+228
</item>
<item>
+690
</item>
<item>
+676
</item>
<item>
+1868
</item>
<item>
+216
</item>
<item>
+90
</item>
<item>
+993
</item>
<item>
+1649
</item>
<item>
+688
</item>
<item>
+1340
</item>
<item>
+256
</item>
<item>
+380
</item>
<item>
+971
</item>
<item>
+44
</item>
<item>
+1
</item>
<item>
+598
</item>
<item>
+998
</item>
<item>
+678
</item>
<item>
+379
</item>
<item>
+58
</item>
<item>
+84
</item>
<item>
+681
</item>
<item>
+212
</item>
<item>
967
</item>
<item>
260
</item>
<item>
263
</item>
</string-array>
<string-array name="country_arrays">
<item>Code</item>
<item>Afghanistan</item>
<item>Albania</item>
<item>Algeria</item>
<item>American Samoa</item>
<item>Andorra</item>
<item>Angola</item>
<item>Anguilla</item>
<item>Antarctica</item>
<item>Antigua and Barbuda</item>
<item>Argentina</item>
<item>Armenia</item>
<item>Aruba</item>
<item>Australia</item>
<item>Austria</item>
<item>Azerbaijan</item>
<item>Bahrain</item>
<item>Bangladesh</item>
<item>Barbados</item>
<item>Belarus</item>
<item>Belgium</item>
<item>Belize</item>
<item>Benin</item>
<item>Bermuda</item>
<item>Bhutan</item>
<item>Bolivia</item>
<item>Bosnia and Herzegovina</item>
<item>Botswana</item>
<item>Bouvet Island</item>
<item>Brazil</item>
<item>British Indian Ocean Territory</item>
<item>British Virgin Islands</item>
<item>Brunei</item>
<item>Bulgaria</item>
<item>Burkina Faso</item>
<item>Burundi</item>
<item>Cambodia</item>
<item>Cameroon</item>
<item>Canada</item>
<item>Cape Verde</item>
<item>Cayman Islands</item>
<item>Central African Republic</item>
<item>Chad</item>
<item>Chile</item>
<item>China</item>
<item>Christmas Island</item>
<item>Cocos (Keeling) Islands</item>
<item>Colombia</item>
<item>Comoros</item>
<item>Congo</item>
<item>Cook Islands</item>
<item>Costa Rica</item>
<item>Cote d\'Ivoire</item>
<item>Croatia</item>
<item>Cuba</item>
<item>Cyprus</item>
<item>Czech Republic</item>
<item>Democratic Republic of the Congo</item>
<item>Denmark</item>
<item>Djibouti</item>
<item>Dominica</item>
<item>Dominican Republic</item>
<item>East Timor</item>
<item>Ecuador</item>
<item>Egypt</item>
<item>El Salvador</item>
<item>Equatorial Guinea</item>
<item>Eritrea</item>
<item>Estonia</item>
<item>Ethiopia</item>
<item>Faeroe Islands</item>
<item>Falkland Islands</item>
<item>Fiji</item>
<item>Finland</item>
<item>Former Yugoslav Republic of Macedonia</item>
<item>France</item>
<item>French Guiana</item>
<item>French Polynesia</item>
<item>French Southern Territories</item>
<item>Gabon</item>
<item>Georgia</item>
<item>Germany</item>
<item>Ghana</item>
<item>Gibraltar</item>
<item>Greece</item>
<item>Greenland</item>
<item>Grenada</item>
<item>Guadeloupe</item>
<item>Guam</item>
<item>Guatemala</item>
<item>Guinea</item>
<item>Guinea-Bissau</item>
<item>Guyana</item>
<item>Haiti</item>
<item>Heard Island and McDonald Islands</item>
<item>Honduras</item>
<item>Hong Kong</item>
<item>Hungary</item>
<item>Iceland</item>
<item>India</item>
<item>Indonesia</item>
<item>Iran</item>
<item>Iraq</item>
<item>Ireland</item>
<item>Israel</item>
<item>Italy</item>
<item>Jamaica</item>
<item>Japan</item>
<item>Jordan</item>
<item>Kazakhstan</item>
<item>Kenya</item>
<item>Kiribati</item>
<item>Kuwait</item>
<item>Kyrgyzstan</item>
<item>Laos</item>
<item>Latvia</item>
<item>Lebanon</item>
<item>Lesotho</item>
<item>Liberia</item>
<item>Libya</item>
<item>Liechtenstein</item>
<item>Lithuania</item>
<item>Luxembourg</item>
<item>Macau</item>
<item>Madagascar</item>
<item>Malawi</item>
<item>Malaysia</item>
<item>Maldives</item>
<item>Mali</item>
<item>Malta</item>
<item>Marshall Islands</item>
<item>Martinique</item>
<item>Mauritania</item>
<item>Mauritius</item>
<item>Mayotte</item>
<item>Mexico</item>
<item>Micronesia</item>
<item>Moldova</item>
<item>Monaco</item>
<item>Mongolia</item>
<item>Montenegro</item>
<item>Montserrat</item>
<item>Morocco</item>
<item>Mozambique</item>
<item>Myanmar</item>
<item>Namibia</item>
<item>Nauru</item>
<item>Nepal</item>
<item>Netherlands</item>
<item>Netherlands Antilles</item>
<item>New Caledonia</item>
<item>New Zealand</item>
<item>Nicaragua</item>
<item>Niger</item>
<item>Nigeria</item>
<item>Niue</item>
<item>Norfolk Island</item>
<item>North Korea</item>
<item>Northern Marianas</item>
<item>Norway</item>
<item>Oman</item>
<item>Pakistan</item>
<item>Palau</item>
<item>Panama</item>
<item>Papua New Guinea</item>
<item>Paraguay</item>
<item>Peru</item>
<item>Philippines</item>
<item>Pitcairn Islands</item>
<item>Poland</item>
<item>Portugal</item>
<item>Puerto Rico</item>
<item>Qatar</item>
<item>Reunion</item>
<item>Romania</item>
<item>Russia</item>
<item>Rwanda</item>
<item>Sqo Tome and Principe</item>
<item>Saint Helena</item>
<item>Saint Kitts and Nevis</item>
<item>Saint Lucia</item>
<item>Saint Pierre and Miquelon</item>
<item>Saint Vincent and the Grenadines</item>
<item>Samoa</item>
<item>San Marino</item>
<item>Saudi Arabia</item>
<item>Senegal</item>
<item>Serbia</item>
<item>Seychelles</item>
<item>Sierra Leone</item>
<item>Singapore</item>
<item>Slovakia</item>
<item>Slovenia</item>
<item>Solomon Islands</item>
<item>Somalia</item>
<item>South Africa</item>
<item>South Georgia and the South Sandwich Islands</item>
<item>South Korea</item>
<item>South Sudan</item>
<item>Spain</item>
<item>Sri Lanka</item>
<item>Sudan</item>
<item>Suriname</item>
<item>Svalbard and Jan Mayen</item>
<item>Swaziland</item>
<item>Sweden</item>
<item>Switzerland</item>
<item>Syria</item>
<item>Taiwan</item>
<item>Tajikistan</item>
<item>Tanzania</item>
<item>Thailand</item>
<item>The Bahamas</item>
<item>The Gambia</item>
<item>Togo</item>
<item>Tokelau</item>
<item>Tonga</item>
<item>Trinidad and Tobago</item>
<item>Tunisia</item>
<item>Turkey</item>
<item>Turkmenistan</item>
<item>Turks and Caicos Islands</item>
<item>Tuvalu</item>
<item>Virgin Islands</item>
<item>Uganda</item>
<item>Ukraine</item>
<item>United Arab Emirates</item>
<item>United Kingdom</item>
<item>United States</item>
<item>United States Minor Outlying Islands</item>
<item>Uruguay</item>
<item>Uzbekistan</item>
<item>Vanuatu</item>
<item>Vatican City</item>
<item>Venezuela</item>
<item>Vietnam</item>
<item>Wallis and Futuna</item>
<item>Western Sahara</item>
<item>Yemen</item>
<item>Yugoslavia</item>
<item>Zambia</item>
<item>Zimbabwe</item>
</string-array>

If you happen to use Google's libphonenumber anyway, and if you work with phone numbers, it's rather likely you do, you can use its internal data that describes the same. It's not public, so you have to use reflection to reach it:
Map<Integer, List<String>> CountryCodeToRegionCodeMap_getCountryCodeToRegionCodeMap() {
try {
Method method = CountryCodeToRegionCodeMap.class.getDeclaredMethod("getCountryCodeToRegionCodeMap");
method.setAccessible(true);
return (Map<Integer, List<String>>) method.invoke(null);
}
catch (Exception e) {
Log.e(..., e.toString());
return null;
}
}
Then you can search or process that map to get the data you want.

I know it way too late. But I have a batter solution of it. Since doing it with the list of String and looping through it might slow it down. Using Hashmap would be a batter solution for it.
I wrote a PhoneUtil class for it. Here is code ( i only have 20 or so countries but you can add more to it )
import android.content.Context;
import android.telephony.TelephonyManager;
import java.util.HashMap;
/**
* Created by Dell on 1/19/2017.
*/
public class PhoneUtil {
public static String getCountryCode(Context context) {
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (manager != null) {
return getCountryCodeFromMap(manager.getSimCountryIso().toUpperCase());
} else {
return null;
}
}
private static String getCountryCodeFromMap(String countryCode) {
HashMap<String, String> countryCodeMap = new HashMap<>();
countryCodeMap.put("TJ", "+992");
countryCodeMap.put("TZ", "+255");
countryCodeMap.put("TH", "+66");
countryCodeMap.put("TG", "+228");
countryCodeMap.put("TK", "+690");
countryCodeMap.put("TO", "+676");
countryCodeMap.put("TN", "+216");
countryCodeMap.put("TR", "+90");
countryCodeMap.put("TM", "+993");
countryCodeMap.put("TV", "+688");
countryCodeMap.put("AE", "+971");
countryCodeMap.put("UG", "+256");
countryCodeMap.put("GB", "+44");
countryCodeMap.put("UA", "+380");
countryCodeMap.put("UY", "+598");
countryCodeMap.put("US", "+1");
countryCodeMap.put("UZ", "+998");
countryCodeMap.put("VU", "+678");
countryCodeMap.put("VA", "+39");
countryCodeMap.put("VE", "+58");
countryCodeMap.put("VN", "+84");
countryCodeMap.put("WF", "+681");
countryCodeMap.put("YE", "+967");
countryCodeMap.put("ZM", "+260");
countryCodeMap.put("ZW", "+263");
countryCodeMap.put( "MY","+60");
countryCodeMap.put("PK","+92");
return countryCodeMap.get(countryCode);
}
}

In class TelephonyManager, I find a method public String getNetworkCountryIso (), this may be what you want. Also, there are some other method which can return more info about the phone. You may read http://en.wikipedia.org/wiki/List_of_mobile_country_codes to see which country is represented by a MCC.

This is code to put in your Main Activity to replace the code that Wais posted near the top of this page. Take the array that Wais posted and add that to your app in the resources. I might have slightly changed the name of the array to be stored in resources, other than that, this code should work well and be easier to read if you are learning:
public String getCountryCode()
{
String my_country_code_letters = getMyLocale().getCountry();
String[] country_codes = this.getResources().getStringArray(R.array.country_codes);
String my_country_code_number = null;
//------------------------------------------------------------------------------------------
for (int i=0; i < country_codes.length && i != (-1); i++)
{
/**split_code:
* 1) split_code[0] == numbers
* 2) split_code[1] == letters**/
String[] split_code = country_codes[i].split(",");
//--------------------------------------------------------------------------------------
if (split_code[1].matches(my_country_code_letters))
{
my_country_code_number = split_code[0];
break;
}
//--------------------------------------------------------------------------------------
}
//------------------------------------------------------------------------------------------
return my_country_code_number;
}
public Locale getMyLocale()
{
Log.i(TAG, "Running getMyLocale()");
Locale myLocale = "";
//------------------------------------------------------------------------------------------
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
{
myLocale = getBaseContext().getResources().getConfiguration().getLocales().get(0);
}
else
{
//noinspection deprecation
myLocale = getBaseContext().getResources().getConfiguration().locale;
}
//------------------------------------------------------------------------------------------
return myLocale;
}

Related

XmlHttpRequest post request doesn't work React Native Android App

In my application, there is a form that users fill and post soap action. This is a must soap because it's a ministry of healt procedure. XmlHttpRequuest post works fine in iOS devices. But doesn't work on android. I did a lot of research but didn't find anything. I am leaving the codes below.Please help me! Thanks!
const soapAction = async (xml, username, password,) => {//here is the post request func
var xmlhttp = new XMLHttpRequest();
xmlhttp.open(
'POST',
'https://*****************************',
);
xmlhttp.timeout = 10000;
var text=xml.toString('utf16');
var sr=
'<?xml version="1.0" encoding="UTF-8"?>'+
'<soap:Envelope' +
' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"' +
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' +
' xmlns:xsd="http://www.w3.org/2001/XMLSchema"' +
' xmlns:xs="http://www.w3.org/2001/XMLSchema"' +
' xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"' +
' xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"' +
' xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">'+
'<soap:Header>'+
'<wsse:Security>'+
'<wsse:UsernameToken wsu:Id="SecurityToken-04ce24bd-9c7c-4ca9-9764-92c53b0662c5">'+
`<wsse:Username>${username}</wsse:Username>`+
`<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">${password}</wsse:Password>`+
'</wsse:UsernameToken>'+
'</wsse:Security>'+
'</soap:Header>'+
'<soap:Body>'+
'<***************************************************">'+
'<input>'+
'<![CDATA[' +
'<?xml version="1.0" encoding="utf-16"?>' +
`${text}`+
']]>'+
'</input>'+
'</**************>'+
'</soap:Body>'+
'</soap:Envelope>';
xmlhttp.setRequestHeader(
'SOAPAction',
'https://*****************************************',
);
xmlhttp.setRequestHeader('Content-Type', 'text/xml; charset=utf-16');
xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "8");
xmlhttp.onload = async function () {
console.log(xmlhttp.responseText);
//alert(xmlhttp.responseText);
if (xmlhttp.responseText.includes("S0000")) {
Alert.alert("Başarılı ", "başarıyla sonuçlandı. ", [
{text: 'Tamam', onPress: () => cancel()},
],
{cancelable: true}
)
} else {
Alert.alert("Hata", "Lütfen Daha Sonra Tekrar Deneyiniz", [
{text: 'Tamam', onPress: () => null},
],
{cancelable: true}
) //it always here because response always null
}
};
xmlhttp.send(sr);
//console.log(xmlhttp);
};
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
//android manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.VIBRATE"/>
<queries>
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:mimeType="*/*" />
</intent>
</queries>
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:usesCleartextTraffic="true"
android:allowBackup="false"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

How To Implement Full Search in Case Type using Salesforce?

I need to build out a solution to create a search field on the new Case Type Data object in all 3 of the Level fields and populate based on selection.
Similar to SF Global Search I would like to type 2-3 characters in the text search field and it would find the matching text in the Level1-3 fields and when selected the Level 1-3 field would populate.
This is the apex class
public class PickListHandler {
#AuraEnabled
public static List<String> getLevel1(){
List<String> tempLst1 = new List<String>();
for(AggregateResult ar : [select Level_1__c,COUNT(id) from Case_Type_Data__c group by Level_1__c])
{
tempLst1.add(''+ar.get('Level_1__c'));
}
return tempLst1;
}
#AuraEnabled
public static List<String> getLevel2(string strName){
List<String> tempLst2 = new List<String>();
for(AggregateResult ar : [select Level_2__c,COUNT(id) from Case_Type_Data__c where Level_1__c=:strName group by Level_2__c])
{
tempLst2.add(''+ar.get('Level_2__c'));
}
return tempLst2;
}
#AuraEnabled
public static List<String> getLevel3(string strName1,string strName2){
List<String> tempLst3 = new List<String>();
for(AggregateResult ar : [select Level_3__c,COUNT(id) from Case_Type_Data__c where Level_1__c=:strName1 and Level_2__c=:strName2 group by Level_3__c])
{
tempLst3.add(''+ar.get('Level_3__c'));
}
return tempLst3;
}
#AuraEnabled
public static String savecasetype(string level1,string level2,string level3,string id){
string strMsg='successfull';
try{
ERT_Case_Type__c obj=new ERT_Case_Type__c();
Obj.Case__c = id;
System.debug('CASE = '+ Obj.Case__c);
Obj.Level_1__c=level1;
System.debug('Level1 = '+ Obj.Level_1__c);
Obj.Level_2__c=level2;
System.debug('Level2 = '+ Obj.Level_2__c);
Obj.Level_3__c=level3;
System.debug('Level3 = '+ Obj.Level_3__c);
Insert obj;
}
catch(Exception ex){
strMsg='error';
}
return strMsg;
}
}
This is the Picklist handler component
<aura:component controller="PickListHandler" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
<!-- Actions-->
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<!-- variable-->
<aura:attribute name="lstLevel1" type="String[]" />
<aura:attribute name="lstLevel2" type="String[]" />
<aura:attribute name="lstL3" type="String[]" />
<span> Level 1</span>
<ui:inputSelect aura:id="ddLevel1" change="{!c.getLvl1}">
<ui:inputSelectOption label="-Select-" value="true"/>
<aura:iteration items="{!v.lstLevel1}" var="value">
<ui:inputSelectOption label="{!value}" text="{!value}" />
</aura:iteration>
</ui:inputSelect>
<span>Level 2</span>
<ui:inputSelect aura:id="ddLevel2" change="{!c.getSelectedValue}">
<ui:inputSelectOption label="-Select-" value="true"/>
<aura:iteration items="{!v.lstLevel2}" var="value">
<ui:inputSelectOption label="{!value}" text="{!value}" />
</aura:iteration>
</ui:inputSelect>
<span>Level 3</span>
<ui:inputSelect aura:id="ddLevel3" >
<ui:inputSelectOption label="-Select-" value="true"/>
<aura:iteration items="{!v.lstL3}" var="value">
<ui:inputSelectOption label="{!value}" text="{!value}" />
</aura:iteration>
</ui:inputSelect>
<lightning:button variant="brand" label="Save" onclick="{!c.onConfirm}" />
</aura:component>
Regards,
Carolyn
You're asking for a lot, we wouldn't have your custom object. And this is old code, ui:inputSelect is deprecated for 1 year now. I'll try to help a bit but the whole thing needs your work too. And examples we can reproduce easily.
I'm going to cheat and use Philippe Ozil's ready component for the lookup/autocomplete thing.
It means you'd have to save LookupSearchResult class, the whole aura component and 2 aura events in your org before reading below. That's some prep work but it's battle-tested :)
Apex class
public with sharing class Stack64129038 {
#AuraEnabled(cacheable=true)
public static List<LookupSearchResult> search(String searchTerm, List<String> selectedIds){
if(String.isBlank(searchTerm) || searchTerm.length() < 2){
return null;
}
String t = '%' + searchTerm + '%'; // decide how you want to search, "starts with", "includes" or what
List<Case_Type_Data__c> records = [SELECT Id, Name, Level_1__c, Level_2__c, Level_3__c
FROM Case_Type_Data__c
WHERE Level_1__c LIKE :t OR Level_2__c LIKE :t OR Level_3__c LIKE :t
ORDER BY Level_1__c, Level_2__c, Level_3__c
LIMIT 20];
/* You could also experiment with SOSL?
records = [FIND :('*' + searchTerm + '*') IN ALL FIELDS
RETURNING Case_Type_Data__c(Id, Name, Level_1__c, Level_2__c, Level_3__c)][0];
*/
List<LookupSearchResult> results = new List<LookupSearchResult>();
for(Case_Type_Data__c ctd : records){
results.add(new LookupSearchResult(ctd.Id, 'Case_Type_Data__c', 'standard:case_wrap_up', ctd.Name,
String.join(new List<String>{ctd.Level_1__c , ctd.Level_2__c, ctd.Level_3__c}, '; ')
));
}
return results;
}
}
Aura component (html part)
<aura:component implements="force:hasRecordId,force:appHostable,flexipage:availableForAllPageTypes,force:lightningQuickAction" access="global" controller="Stack64129038">
<aura:attribute access="private" type="List" name="selection" default="[]"/>
<aura:attribute access="private" type="List" name="errors" default="[]"/>
<lightning:card title="New Case Type">
<lightning:recordEditForm aura:id="myForm" objectApiName="ERT_Case_Type__c" onsubmit="{!c.onSubmit}" onsuccess="{!c.onSuccess}">
<lightning:messages />
<c:Lookup selection="{!v.selection}" onSearch="{!c.lookupSearch}" onSelection="{!c.useSelected}" errors="{!v.errors}" label="Search" placeholder="Search Case Types Data"/>
<lightning:inputField aura:id="Level_1__c" fieldName="Level_1__c" />
<lightning:inputField aura:id="Level_2__c" fieldName="Level_2__c" />
<lightning:inputField aura:id="Level_3__c" fieldName="Level_3__c" />
<lightning:button class="slds-m-top_small" variant="brand" type="submit" name="save" label="Save" />
</lightning:recordEditForm>
</lightning:card>
</aura:component>
Aura component - JS controller part
({
lookupSearch : function(component, event, helper) {
// Get the lookup component that fired the search event
const lookupComponent = event.getSource();
const serverSearchAction = component.get('c.search');
lookupComponent.search(serverSearchAction);
},
useSelected: function(component, event, helper) {
const selection = component.get('v.selection');
const errors = component.get('v.errors');
if (selection.length) {
if(errors.length){ // Clear errors, if any
component.set('v.errors', []);
}
let levels = selection[0].subtitle.split('; ');
component.find('Level_1__c').set('v.value', levels[0]);
component.find('Level_2__c').set('v.value', levels[1]);
component.find('Level_3__c').set('v.value', levels[2]);
}
},
onSubmit: function(component, event, helper) {
debugger;
event.preventDefault(); // stop the form from submitting
var fields = event.getParam('fields');
fields.Case__c = component.get('v.recordId'); // link to "this" Case
component.find('myForm').submit(fields);
},
onSuccess: function(component, event, helper){
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"title": "Success!",
"message": "Case Type saved OK, refreshing",
"type": "success"
});
toastEvent.fire();
$A.get('e.force:refreshView').fire(); // reload page
}
})

Powershell: Copy Elements from one array to another

Hi in my first array there are my nodes from a xml.
$result=Select-xml -xml $uar -xpath "//test:UAVariable[contains(#NodeId,'ns=1;s=::')][starts-with(#DataType,'i=')]" -namespace $ns | select -ExpandProperty node
now i have to filter this further more like this. And then if both if´s are true delete the element from my array if its possible or copy this Element to a new one.
$result | foreach {
$AttExists = $_.Arraydimensions
$NodeExists = $_.References.Reference.ReferenceType
if ($AttExists){
if ($NodeExists -eq 'HasComponent'){
#if this is happening i want to delete this hole Element (Node) in my array is this possible?
}
else{
#if deleting is not possible i want to copy these Element (Node) into a new array is this possible?
}
}
}
Tried several things like:
$_=$nullor whith a counter like $newArray[$i] = $result[$j] $i++
But it dont delete anything or copy it. Can someone help me?
xml data :
<?xml version="1.0" encoding="utf-8"?>
<UANodeSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:uax="http://opcfoundation.org/UA/2008/02/Types.xsd" xmlns:ua="http://xxx/NodeSet.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pv="http://yyy/NodeSet.xsd" xmlns="http://opcfoundation.org/UA/2011/03/UANodeSet.xsd">
<UAObject NodeId="ns=1;s=::" BrowseName="1:::">
<DisplayName><Default></DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">ns=2;i=10001</Reference>
<Reference ReferenceType="Organizes" IsForward="false">ns=2;i=20001</Reference>
<Reference ReferenceType="Organizes">ns=1;s=::AsGlobalPV</Reference>
<Reference ReferenceType="Organizes">ns=1;s=::Program</Reference>
</References>
<Extensions>
<Extension>
<pv:ObjectExtension>
<ACL>
<ACE Role="1" Allow="0x017F"/>
<ACE Role="2" Allow="0x015F"/>
</ACL>
</pv:ObjectExtension>
</Extension>
</Extensions>
</UAObject>
<UAObject ParentNodeId="ns=1;s=::" NodeId="ns=1;s=::AsGlobalPV" BrowseName="1:Global PV">
<DisplayName>Global PV</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">i=61</Reference>
<Reference ReferenceType="Organizes" IsForward="false">ns=1;s=::</Reference>
<Reference ReferenceType="Organizes">ns=1;s=::AsGlobalPV:gFahrzeug</Reference>
<Reference ReferenceType="Organizes">ns=1;s=::AsGlobalPV:gLebewesen</Reference>
</References>
</UAObject>
<UAVariable DataType="ns=1;i=100000" ParentNodeId="ns=1;s=::AsGlobalPV" NodeId="ns=1;s=::AsGlobalPV:gFahrzeug" BrowseName="1:gFahrzeug" AccessLevel="3" ValueRank="-1">
<DisplayName>gFahrzeug</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">ns=1;i=100005</Reference>
<Reference ReferenceType="HasComponent">ns=1;s=::AsGlobalPV:gFahrzeug.Kraftfahrzeug</Reference>
</References>
<Extensions>
<Extension>
<pv:VariableExtension AuditEvents="true">
<Value>
<Binding Type="PV" Target="::gFahrzeug"/>
</Value>
</pv:VariableExtension>
</Extension>
</Extensions>
</UAVariable>
<UAVariable DataType="ns=1;i=100010" ParentNodeId="ns=1;s=::AsGlobalPV:gFahrzeug" NodeId="ns=1;s=::AsGlobalPV:gFahrzeug.Kraftfahrzeug" BrowseName="1:Kraftfahrzeug" AccessLevel="3" ValueRank="-1">
<DisplayName>Kraftfahrzeug</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">ns=1;i=100015</Reference>
<Reference ReferenceType="HasComponent">ns=1;s=::AsGlobalPV:gFahrzeug.Kraftfahrzeug.LKW</Reference>
<Reference ReferenceType="HasComponent">ns=1;s=::AsGlobalPV:gFahrzeug.Kraftfahrzeug.PKW</Reference>
</References>
<Extensions>
<Extension>
<pv:VariableExtension AuditEvents="true">
<Value>
<Binding Type="PV" Target="::gFahrzeug.Kraftfahrzeug"/>
</Value>
</pv:VariableExtension>
</Extension>
</Extensions>
</UAVariable>
<UAVariable DataType="i=3" ParentNodeId="ns=1;s=::AsGlobalPV:gFahrzeug.Kraftfahrzeug" NodeId="ns=1;s=::AsGlobalPV:gFahrzeug.Kraftfahrzeug.LKW" BrowseName="1:LKW" AccessLevel="3" ValueRank="1" ArrayDimensions="2">
<DisplayName>LKW</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">i=63</Reference>
<Reference ReferenceType="HasComponent">ns=1;s=::AsGlobalPV:gFahrzeug.Kraftfahrzeug.LKW[0]</Reference>
<Reference ReferenceType="HasComponent">ns=1;s=::AsGlobalPV:gFahrzeug.Kraftfahrzeug.LKW[1]</Reference>
</References>
<Extensions>
<Extension>
<pv:VariableExtension AuditEvents="true">
<Value>
<Binding Type="PV" Target="::gFahrzeug.Kraftfahrzeug.LKW"/>
</Value>
</pv:VariableExtension>
</Extension>
</Extensions>
</UAVariable>
<UAVariable DataType="i=3" ParentNodeId="ns=1;s=::AsGlobalPV:gFahrzeug.Kraftfahrzeug.LKW" NodeId="ns=1;s=::AsGlobalPV:gFahrzeug.Kraftfahrzeug.LKW[0]" BrowseName="1:LKW[0]" AccessLevel="3">
<DisplayName>LKW[0]</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">i=63</Reference>
</References>
<Extensions>
<Extension>
<pv:VariableExtension AuditEvents="true">
<ACL>
<ACE Role="1" Allow="0x017F"/>
<ACE Role="2" Allow="0x015F"/>
</ACL>
<Value>
<Binding Type="PV" Target="::gFahrzeug.Kraftfahrzeug.LKW[0]"/>
</Value>
</pv:VariableExtension>
</Extension>
</Extensions>
</UAVariable>
<UAVariable DataType="i=3" ParentNodeId="ns=1;s=::AsGlobalPV:gFahrzeug.Kraftfahrzeug.LKW" NodeId="ns=1;s=::AsGlobalPV:gFahrzeug.Kraftfahrzeug.LKW[1]" BrowseName="1:LKW[1]" AccessLevel="3">
<DisplayName>LKW[1]</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">i=63</Reference>
</References>
<Extensions>
<Extension>
<pv:VariableExtension AuditEvents="true">
<ACL>
<ACE Role="1" Allow="0x017F"/>
<ACE Role="2" Allow="0x015F"/>
</ACL>
<Value>
<Binding Type="PV" Target="::gFahrzeug.Kraftfahrzeug.LKW[1]"/>
</Value>
</pv:VariableExtension>
</Extension>
</Extensions>
</UAVariable>
</UANodeSet>
Code:
[xml]$uar = Get-Content -Path 'C:\Users\strobel.ma\OneDrive - GEA\Desktop\XML to String\OpcUaMap(3)_28_07.uar'
$ns = New-Object System.Xml.XmlNamespaceManager($uar.NameTable) #asdf
$ns=#{GEA="http://opcfoundation.org/UA/2011/03/UANodeSet.xsd";
ua="http://br-automation.com/OpcUa/configuration/NodeSet.xsd";
xsi="http://www.w3.org/2001/XMLSchema-instance";
uax="http://opcfoundation.org/UA/2008/02/Types.xsd";
xsd="http://www.w3.org/2001/XMLSchema";
pv="http://br-automation.com/OpcUa/PLC/PV.xsd"}
$result=Select-xml -xml $uar -xpath "//GEA:UAVariable[contains(#NodeId,'ns=1;s=::')][starts-with(#DataType,'i=')]" -namespace $ns | select -ExpandProperty node
$result | foreach {$_.NodeId = $_.NodeId -replace 'ns=1;s=::AsGlobalPV:'}
$result | foreach {$_.NodeId = $_.NodeId -replace 'ns=1;s=::'}
$result | foreach {
$AttExists = $_.Arraydimensions
$NodeExists = $_.References.Reference.ReferenceType
if ($AttExists){
if ($NodeExists -eq 'HasComponent'){
#if this is happening i want to delete this hole Element (Node) in my array is this possible?
}
else{
#if deleting is not possible i want to copy these Element (Node) into a new array is this possible?
}
}
}
I would suggest you a naive approach and just create a new $result2 object where you store exactly what you need
I guess the default System.Array type should be good enough:
declare the new variable where to store items:
$result2 = #()
and store in it whatever you want by using in your foreach loop the following:
$result2 += $_

Flat file to json conversion using beanIo

I am trying to parse a fixedlength flat file using beanIo to json
Code:
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import org.beanio.BeanIOConfigurationException;
import org.beanio.BeanReader;
import org.beanio.StreamFactory;
import org.junit.Test;
import com.google.gson.Gson;
public class EmployeeBeanIOHandlerTest {
#Test
public void testHandleEmployee() {
// mapping pattern file
String mappingPatternFile = "pattern-mapping.xml";
// data file (csv)
String objectFile = "employee.csv";
// stream name defined in pattern mapping file
String streamName = "empData";
Gson gson = new Gson();
BeanReader beanReader = null;
Reader reader = null;
StreamFactory factory = null;
InputStream in = null;
try {
System.out.println("## RESULT FOR " + objectFile + " ##");
// create a StreamFactory
factory = StreamFactory.newInstance();
// load the setting file
in = this.getClass().getClassLoader()
.getResourceAsStream(mappingPatternFile);
// get input stream reader of object file (data file)
reader = new InputStreamReader(this.getClass().getClassLoader()
.getResourceAsStream(objectFile));
// load input stream to stream factory
factory.load(in);
beanReader = factory.createReader(streamName, reader);
Map<?, ?> record = null;
while ((record = (Map<?, ?>) beanReader.read()) != null) {
System.out.println(beanReader.getRecordName() + ": "
+ gson.toJson(record));
}
} catch (BeanIOConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
if (beanReader != null) {
beanReader.close();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
However the output i see:
header: {"id":"Header","date":"01012013"}
emp: {"lastName":"Lilik","title":"Senior Developer","hireDate":"Oct 1, 2009
12:00:00 AM","salary":7500000,"firstName":"Robertus"}
emp: {"lastName":"Doe","title":"Architect","hireDate":"Jan 15, 2008 12:00:00 AM","salary":8000000,"firstName":"Jane"}
emp: {"lastName":"Anderson","title":"Manager","hireDate":"Mar 18, 2006 12:00:00 AM","salary":9000000,"firstName":"Jon"}
trailer: {"id":"Trailer","count":"3"}
Which generates separate json object for each record found.
Reference site:
http://www.sourcefreak.com/2013/06/painless-flat-file-parsing-with-beanio/
Below is my requirement:
I want to have a consolidated Json file.
In case of duplicate record it should form an json array.
I would appreciate a help on this.
This answer is based on the data and pattern-mapping.xml file found in the link provided by the OP.
Data:
Header,01012013
Robertus,Lilik,Senior Developer,"75,000,00",10012009
Jane,Doe,Architect,"80,000,00",01152008
Jon,Anderson,Manager,"90,000,00",03182006
Footer,3
Mapping File:
This is the modified pattern-mapping.xml file. Note the use of a <group> element (myGroup) to encapsulate everything into a single group, which will force the BeanReader to read everything in one go. I also changed the maxOccurs to be 1 (one) for both the Header and the Footer records. Also, added the collection="list" attribute to theemp` record
<?xml version='1.0' encoding='UTF-8' ?>
<beanio xmlns="http://www.beanio.org/2012/03"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.beanio.org/2012/03 http://www.beanio.org/2012/03/mapping.xsd">
<stream name="empData" format="csv">
<group name="myGroup" class="map">
<record name="header" class="map" ridLength="0-2" maxOccurs="1">
<field name="id" rid="true" maxOccurs="1" literal="Header" />
<field name="date" />
</record>
<record name="emp" class="map" ridLength="4-5" collection="list">
<field name="firstName" />
<field name="lastName" />
<field name="title" />
<field name="salary" type="java.math.BigDecimal" format="#,###,###,00" />
<field name="hireDate" type="java.util.Date" format="MMddyyyy" minOccurs="0" />
</record>
<record name="trailer" class="map" ridLength="2" maxOccurs="1">
<field name="id" />
<field name="count" />
</record>
</group>
</stream>
</beanio>
Using the test case supplied and the modified mapping file, we get this result (reformatted by me):
myGroup: {
"trailer": {
"count": "3",
"id": "Footer"
},
"header": {
"date": "01012013",
"id": "Header"
},
"emp": [
{
"firstName": "Robertus",
"lastName": "Lilik",
"hireDate": "Oct 1, 2009 12:00:00 AM",
"title": "Senior Developer",
"salary": 7500000
},
{
"firstName": "Jane",
"lastName": "Doe",
"hireDate": "Jan 15, 2008 12:00:00 AM",
"title": "Architect",
"salary": 8000000
},
{
"firstName": "Jon",
"lastName": "Anderson",
"hireDate": "Mar 18, 2006 12:00:00 AM",
"title": "Manager",
"salary": 9000000
}
]
}
Hope this helps

msbuild itemgroup items

I have msbuild file which is executing batch file.
Msbuild file:
<PropertyGroup>
<ItemAString>Green;Red;Blue</ItemAString>
<ItemBString>Uno;Due;Tre</ItemBString>
<ItemCString>Song;Movie;Picture</ItemCString>
</PropertyGroup>
<ItemGroup>
<ItemsA Include="$(ItemAString.Split(';'))" />
<ItemsB Include="$(ItemBString.Split(';'))" />
<ItemsC Include="$(ItemCString.Split(';'))" />
</ItemGroup>
<Target Name = "CallBatch">
<!-- THIS DOES NOT WORK -->
<Exec Command="mybatch.bat %(ItemsA.Identity) %(ItemsB.Identity) %(ItemsC.Identity)" />
</Target>
Batch file is very simple:
echo Params = [%1] - [%2] - [%3]
I want to get next output:
Params = Green - Uno - Song
Params = Red - Due - Movie
Params = Blue - Movie - Picture
How to achieve this?
I found solution:
<Project DefaultTarget="DoTheMagic" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="12.0">
<PropertyGroup Condition=" '$(TFP)'=='' ">
<TFP>$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll</TFP>
<TFP Condition=" !Exists('$(TFP)')">$(MSBuildFrameworkToolsPath)\Microsoft.Build.Tasks.v4.0.dll</TFP>
<TFP Condition=" !Exists('$(TFP)')">$(windir)\Microsoft.NET\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll</TFP>
</PropertyGroup>
<UsingTask
TaskName="Bukake"
TaskFactory="CodeTaskFactory"
AssemblyFile="$(TFP)" >
<ParameterGroup>
<ItemsA Required="True" ParameterType="System.String"/>
<ItemsB Required="True" ParameterType="System.String"/>
<ItemsC Required="True" ParameterType="System.String"/>
<Result ParameterType="Microsoft.Build.Framework.ITaskItem[]" Output="True"/>
</ParameterGroup>
<Task>
<Code Type="Fragment" Language="cs">
<![CDATA[
string[] itemsA = ItemsA.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries);
string[] itemsB = ItemsB.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries);
string[] itemsC = ItemsC.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
List<TaskItem> items = new List<TaskItem>();
for (int index = 0; index < itemsA.Length; index++)
{
TaskItem item = new TaskItem();
item.ItemSpec = "item";
item.SetMetadata("itemA", itemsA[index]);
item.SetMetadata("itemB", itemsB[index]);
item.SetMetadata("itemC", itemsC[index]);
items.Add(item);
}
Result = items.ToArray();
]]>
</Code>
</Task>
</UsingTask>
<PropertyGroup>
<ItemAString>Green;Red;Blue</ItemAString>
<ItemBString>Uno;Due;Tre</ItemBString>
<ItemCString>Song;Movie;Picture</ItemCString>
</PropertyGroup>
<Target Name = "CallBatch">
<Message Text="$(TFS)" />
<Bukake ItemsA="$(ItemAString)"
ItemsB="$(ItemBString)"
ItemsC="$(ItemCString)">
<Output TaskParameter="Result" ItemName="Dundonja" />
</Bukake>
<ItemGroup>
<PreparedItems Include="#(Dundonja)"/>
</ItemGroup>
<!-- <Message Text="Dundonja: %(Dundonja.Identity) %(Dundonja.itemA) %(Dundonja.itemB) %(Dundonja.itemC)"/> -->
<Exec Command="mybatch.bat Dundonja %(Dundonja.Identity) %(Dundonja.itemA) %(Dundonja.itemB) %(Dundonja.itemC)"/>
</Target>

Resources