How to get ISO Country code in android applications? - android

I am a new developer on android application. I would like to get the ISO Country code when I pass the mobile number with country code. If I pass the mobile number as 1-319-491-6338, can I get country ISO code as US / USA in android?
I have written the code as follows:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();
String mobileno="1-319-491-6338";
Here, where can I pass the mobile number?
Can anybody please help me ?
Thanks in advance

You may not be able to query the country code programmatically via the standard API but you could include a table in your app. Such a table is easily found via Google (e.g. http://countrycode.org/).
Danger Will Robinson!: However, one should ask yourself what question you are trying to answer. Implicit in your question is that assumption that there is a one-to-one mapping between international dialling codes and ISO country codes. This is not true. For example, both the USA and Canada have the international dialling code '1'.
Perhaps think about re-structuring your app's interface. Allow the user to select a country to associate with the phone number but use the table from http://countrycode.org/ to order the most likely candidates at the top?

Had the same problem. Eventually I put all the data in excel and read the excel sheet.
Here is the implementation:
copy-past the country code table from http://countrycode.org/ to Microsoft Excel file.
Save the Excel file as 97-2003 compatible (.xls) in \res\raw\countrycode_org.xls
Download JExcelApi from here
Use the following class to read the file:
public class CountryCodes {
private HashMap mCountryByName = new HashMap();
private HashMap mCountryByCode = new HashMap();;
private ArrayList mCountries = new ArrayList();
public void addCountry(String countryName,String ISO_code,String countryCode){
countryCode = PhoneNumberUtil.normalizeDigitsOnly(countryCode);
Country country = new Country();
country.Name = countryName;
country.Code = countryCode;
country.ISO_code = ISO_code;
mCountryByName.put(countryName, country);
mCountryByCode.put(countryCode, country);
mCountries.add(country);
return;
}
public Country getCountryByCode(String countryCode){
countryCode = PhoneNumberUtil.normalizeDigitsOnly(countryCode);
return mCountryByCode.get(countryCode);
}
public Country getCountryByName(String countryName){
return mCountryByName.get(countryName);
}
public Country getCountryByIsoCode(String ISO_code){
ISO_code = ISO_code.toUpperCase();
for (Country country:mCountries){
String [] strArr = country.ISO_code.split("/| ");
for (String s:strArr){
if (ISO_code.equals(s))
return country;
}
}
return null;
}
public String[] getCountryNamesList(){
String[] res = new String [mCountries.size()];
int i=0;
for (Country c:mCountries){
res[i] = c.Name;
i++;
}
return res;
}
public void readCountryCodesFromExcelWorkbook()
{
Context context = GlobalData.getInstance().getApp();
Workbook mWorkbook;
InputStream myRawResource = context.getResources().openRawResource(R.raw.countrycode_org);
if (myRawResource == null)
Toast.makeText(context,"XML file not found",Toast.LENGTH_LONG).show();
else
try {
WorkbookSettings ws = new WorkbookSettings();
ws.setEncoding("Cp1252");
mWorkbook = Workbook.getWorkbook(myRawResource);
//ArrayList<String[]> currentSheet = new ArrayList<String[]>();
Sheet sheet = mWorkbook.getSheet(0);
int rowsNum = sheet.getRows();
for (int rowNum = 1; rowNum < rowsNum; rowNum++) {
//Log.d("RowNum", ""+rowNum);
int colsNum = sheet.getColumns();
String[] strArr = new String[colsNum];
boolean rowIsFull = true;
for (int colNum = 0; colNum < colsNum; colNum++) {
strArr[colNum] = sheet.getCell(colNum, rowNum).getContents();
if (strArr[colNum].length() == 0)
rowIsFull = false;
}
if (rowIsFull)
addCountry(strArr[0],strArr[1],strArr[2]);
}
} catch (BiffException e) {
Toast.makeText(context,"Error Reading xml file: BiffException",Toast.LENGTH_LONG).show();
e.printStackTrace();
return ;
} catch (IOException e) {
Toast.makeText(context,"Error Reading xml file: IOException",Toast.LENGTH_LONG).show();
e.printStackTrace();
return ;
}
}
public Country[] getCountries(){
return mCountries.toArray(new Country[0]);
}
public class Country {
public String Name;
public String Code;
public String ISO_code;
}
}

Step-1
You can get country calling code as well as its ISO name in the following URL
http://en.wikipedia.org/wiki/List_of_country_calling_codes
or
http://www.unc.edu/~rowlett/units/codes/country.htm
Step-2 You can get page source of that file using java program. You will get file in HTMl format
Step-3 you can convert those HTML files into XML format using any of available parsers. see Open Source HTML Parsers in Java
Step-4 Form the phone number you can get the calling code. Example if the number is "1-319-491-6338" then calling code is 1
Step-5 Match this calling code against the calling code and country name list that you have got from XML parser. In this way you can get iso country

Related

Get user phone number in USA format

I want to fetch phone number X(XXX)XXX-XXX in this format and when I Google I found PhoneNumberUtils.formatNumber() but it gives the number in this format X-XXX-XXX-XXX so how can I get the number in X(XXX)XXX-XXX fromat.
Code
holder.tv_vehicle.setText("Phone #: " + PhoneNumberUtils.formatNumber(data.getUserPhone()));
PhoneNumberUtils.formatNumber will return (XXX)XXX-XXX if you pass a local number and X-XXX-XXX-XXX for international number , in your case you have 2 solutions :
Remove the country code then parse the phone number
String phoneNumber = "+1-202-000-0000";
String code = result.substring(0,3);
String localNumber = result.replace(code,""); //202-555-0196
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.i("result",code.replace("-","") + PhoneNumberUtils.formatNumber(localNumber , "US"));
} else {
Log.i("result",code.replace("-","") + PhoneNumberUtils.formatNumber(localNumber));
}
Result : +1(202) 000-0000
Use this library google/libphonenumber for formatting international phone numbers.
private String getFormattedNumber(String phoneNumber) {
PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
Phonemetadata.NumberFormat numberFormat = new Phonemetadata.NumberFormat();
numberFormat.pattern = "(\\d{3})(\\d{3})(\\d{4})";
numberFormat.format = "($1) $2-$3";
List<Phonemetadata.NumberFormat> newNumberFormats = new ArrayList<>();
newNumberFormats.add(numberFormat);
Phonenumber.PhoneNumber phoneNumberPN = null;
try {
phoneNumberPN = phoneNumberUtil.parse(phoneNumber, Locale.US.getCountry());
phoneNumber = phoneNumberUtil.formatByPattern(phoneNumberPN, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL, newNumberFormats);
} catch (NumberParseException e) {
e.printStackTrace();
}
return phoneNumber;
}
getFormattedNumber("+12020000000");
Result : +1(202) 000-0000
holder.tv_vehicle.setText("Phone #: " + PhoneNumberUtils.formatNumber(data.getUserPhone()).replaceFirst("-", "(").replaceFirst("-", ")"));
You can use replaceFirst() to insert ( then ) and convert it. I wrote a little bit of a bad code here that should work. If I was doing it in my own program, I would make it into a function that did this and returned the updated string.

Android: Convert Json string into List and vice versa

I was looking for an example and alive code to transfer just a list of objects into Json string and vice versa.
It is not a secret, that Androids are often used as a communication devices between (in my case) PC with .NET and the Android device itself.
The very common operation is to send SMS messages to a group of subscribers, that's usually exists as a List of objects.. say..
class Man {
public string Number {get;set;}
public string Message {get;set;}
}
So, the List<Man> Men = new List<Man>();
is quite intuitive as the basic structure.
I can convert both ways in C#.NET
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
public static void Main() {
List<Man> Men = new List<Man>();
// numbers are just random
Man m1 = new Man();
m1.Number = "+6149168158";
m1.Message = "Hello Bob from 1";
m1.UniqueCode = "0123";
m1.State = 0;
Man m2 = new Man();
m2.Number = "+6146146182";
m2.Message = "Hello Bob from 2";
m2.UniqueCode = "0125";
m2.State = 0;
Men.AddRange(new Man[] { m1, m2 });
string result = JsonConvert.SerializeObject(Men);
Console.WriteLine(result);
List<Man> men = JsonConvert.DeserializeObject<List<ManĀ»(result);
foreach(Man m in men) Console.WriteLine(m.Message);
}
}
public class Man
{
public string Number{get;set;}
public string Message {get;set;}
public string UniqueCode {get;set;}
public int State {get;set;}
}
It works.. but the Android side.. just like a dark matter.. I am sure it exists, but I can't touch it..
So, please, whoever knows it, please, publish the Android part here, so the others would get nice and clear example for such a standard requirement.
(No Gson, Mason or some others.. only Android and only JSON..
Thank you..
It looks like you might not want to use the tools available( Gson, Mason or some others..)
You must manually implement your mapper class for every object:
Native tools for android are JSONArray,JSONObject;
In the following code I have provided an example of decoding
Ok, this is the Deserializator
public List<Man> DecodeFactor(String json) throws JSONException {
List<Man> list = null;
try
{
JSONArray headarrays=new JSONArray(json);
if(headarrays.length()>0)
{
list=new ArrayList<Man>();
for (int i = 0; i <headarrays.length() ; i++)
{
Man man=new Man();
JSONObject o = headarrays.getJSONObject(i);
man.Message = o.getString("Message");
man.Number = o.getString("Number");
man.UniqueCode = o.getString("UniqueCode");
man.State = o.getInt("State");
list.add(man);
}
}
}catch (Exception ee) { ee.printStackTrace(); }
return list;
}

Download here map for a country directly (without selecting it)

I have to download here map for my country without using the complex UI for selecting it.
Simply I need to detect the country somehow and download the offline map for the country from here.
I know this will fix the problem.
List<Integer> idList = new ArrayList<>();
idList.add(country.getId());
mMapLoader.installMapPackages(idList)
But I don't know how to get the MapPackage country object .
I don't want to implement a list UI and select country from it.
I want to detect my MapPackage country and download it directly.
You can use the locale of the device to find the country:
String locale = context.getResources().getConfiguration().locale.getDisplayCountry();
or you can use the location through the sim used in the phone by the user:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();
below is the code for country code
String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(UserIP))
{
UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
string url = "http://freegeoip.net/json/" + UserIP.ToString();
WebClient client = new WebClient();
string jsonstring = client.DownloadString(url);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
System.Web.HttpContext.Current.Session["UserCountryCode"] = dynObj.country_code;
Using the above function you can get Country code so that you can directly pass it as a parameter to your function
ex: mMapLoader.installMapPackages(System.Web.HttpContext.Current.Session["UserCountryCode"])
below is the code for country code
String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(UserIP))
{
UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
string url = "http://freegeoip.net/json/" + UserIP.ToString();
WebClient client = new WebClient();
string jsonstring = client.DownloadString(url);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
System.Web.HttpContext.Current.Session["UserCountryCode"] = dynObj.country_code;
Using the above function you can get Country code so that you can directly pass it as a parameter to your function
ex: mMapLoader.installMapPackages(System.Web.HttpContext.Current.Session["UserCountryCode"])
In Java
public static final Map<String, String> COUNTRY_MAP;
static {
Map<String, String> map = new HashMap<String, String>();
map.put("AF", "afghanistan"); // here put your country dynamically
map.put("AL", "albania");
...
map.put("ZW", "zimbabwe");
COUNTRY_MAP = Collections.unmodifiableMap( map );
}

How to split a string and get a specific string in android?

I want to split a string and get a word finally. My data in database is as follows.
Mohandas Karamchand Gandhi (1869-1948), also known as Mahatma Gandhi, was born in Porbandar in the present day state of Gujarat in India on October 2, 1869.
He was raised in a very conservative family that had affiliations with the ruling family of Kathiawad. He was educated in law at University College, London.
src="/Leaders/gandhi.png"
From the above paragraph I want get the image name "gandhi". I am getting the index of "src=". But now how can I get the image name i.e "gandhi" finally.
My Code:
int index1;
public static String htmldata = "src=";
if(paragraph.contains("src="))
{
index1 = paragraph.indexOf(htmldata);
System.out.println("index1 val"+index1);
}
else
System.out.println("not found");
You can use the StringTokenizer class (from java.util package ):
StringTokenizer tokens = new StringTokenizer(CurrentString, ":");
String first = tokens.nextToken();// this will contain one word
String second = tokens.nextToken();// this will contain rhe other words
// in the case above I assumed the string has always that syntax (foo: bar)
// but you may want to check if there are tokens or not using the hasMoreTokens method
Try this code. Check if it working for you..
public String getString(String input)
{
Pattern pt = Pattern.compile("src=.*/(.*)\\..*");
Matcher mt = pt.matcher(input);
if(mt.find())
{
return mt.group(1);
}
return null;
}
Update:
Change for multiple item -
public ArrayList<String> getString(String input)
{
ArrayList<String> ret = new ArrayList<String>();
Pattern pt = Pattern.compile("src=.*/(.*)\\..*");
Matcher mt = pt.matcher(input);
while(mt.find())
{
ret.add(mt.group(1));
}
return ret;
}
Now you'll get an arraylist with all the name. If there is no name then you'll get an empty arraylist (size 0). Always make a check for size.

android XML parse into Hash map not working

I am getting the most bizzarre behavior with trying to parse an XML, I run through it step by step and all values are assigned and retrieved in order and then the object I create is added to a HashMap for easy look up, the problem is when I am done retrieving it all the HashMap has null values and the ones that aren't null are the value of the very last node that was read, I have walked through it over and over and it all seems correct, but when it's done loading the values in the HasMap look like:
[0] null
[1] NarrationItem#44e9d170
[2] null
[3] null
[4] NarrationItem#44e9d170
etc, etc.
The format of my XML files is:
<narrations>
<narration id="0" name="A" alias="a" >
<line text="This is a test."></line>
</narration>
<narration id="1" name="B" alias="b" >
<line text="This another a test."></line>
</narration>
<narration id="2" name="C" alias="c" >
<line text="This is STILL a test."></line>
</narration>
</narrations>
And my XML parsing method is follows:
public HashMap<String, NarrationItem> NarrationMap = new HashMap<String, NarrationItem>();
private void LoadNarrationsXML() {
NarrationItem i = new NarrationItem();
String line;
String s;
try {
// Get the Android-specific compiled XML parser.
XmlResourceParser xmlParser = this.getResources().getXml(R.xml.narrations);
while (xmlParser.getEventType() != XmlResourceParser.END_DOCUMENT) {
if (xmlParser.getEventType() == XmlResourceParser.START_TAG) {
s = xmlParser.getName();
if (s.equals("narration")) {
i.Clear();
i.ID = xmlParser.getAttributeIntValue(null, "id", 0);
i.Name = xmlParser.getAttributeValue(null, "name");
i.Alias = xmlParser.getAttributeValue(null, "alias");
} else if (s.equals("line")) {
line = xmlParser.getAttributeValue(null, "text");
i.Narration.add(line);
}
} else if (xmlParser.getEventType() == XmlResourceParser.END_TAG) {
s = xmlParser.getName();
if (s.equals("narration")) {
NarrationMap.put(i.Alias, i);
}
}
xmlParser.next();
}
xmlParser.close();
} catch (XmlPullParserException xppe) {
Log.e(TAG, "Failure of .getEventType or .next, probably bad file format");
xppe.toString();
} catch (IOException ioe) {
Log.e(TAG, "Unable to read resource file");
ioe.printStackTrace();
}
}
The NarrationItem object is a custom object defined as:
public class NarrationItem {
int ID;
String Name;
String Alias;
ArrayList<String> Narration = new ArrayList<String>();
public NarrationItem() { }
public void LoadNarration(int id, String name, String alias, ArrayList<String> narration) {
ID = id;
Name = name;
Alias = alias;
Narration.addAll(narration);// = narration;
}
public void Clear() {
ID = 0;
Name = "";
Alias = "";
Narration.clear();
}
}//End Narration
If someone could point out the problem I'd be very thankful I have sat here staring at this issue for hours.
You're only ever creating one NarrationItem object - you're then using a reference to that object as the value for multiple entries in the map. Don't do that. You need to understand that the map doesn't contain an object as the value - it contains a reference to an object.
You can probably fix this just by creating a new NarrationItem each time instead of calling Clear.
It's not clear how you're looking at the map to see those null values, but if you're using the debugger and looking at the internal data structure, you probably shouldn't really be doing that either - instead, step through the keys, values or entries, i.e. stick within the abstraction that HashMap is meant to support.

Categories

Resources