android: how do I format number as phone with parentheses - android

I have a number that I need to format as a telephone number. If I do
PhoneNumberUtils.formatNumber(numStr);
Then I get
888-555-1234
But what I need to get is
(888) 555-1234
How do I get the second one? Is there a standard android way?

If you know the country for which you want to do it, you can use Google's open source library libphonenumber . Here is how you can format it:
String numberStr = "8885551234"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber numberProto = phoneUtil.parse(numberStr, "US");
//Since you know the country you can format it as follows:
System.out.println(phoneUtil.format(numberProto, PhoneNumberFormat.NATIONAL));
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
If you don't know the country then for numberStr use E.164 format phone number and in place of country code use null.

Don't know if you found what you were looking for, but I ended up writing a little method that takes the length of a string (since the phone numbers I get come from a web service and can be a variety of formats). I believe it should work (so far all my test cases have been with the first two options -- haven't tested the other two yet).
public static String FormatStringAsPhoneNumber(String input) {
String output;
switch (input.length()) {
case 7:
output = String.format("%s-%s", input.substring(0,3), input.substring(3,7));
break;
case 10:
output = String.format("(%s) %s-%s", input.substring(0,3), input.substring(3,6), input.substring(6,10));
break;
case 11:
output = String.format("%s (%s) %s-%s", input.substring(0,1) ,input.substring(1,4), input.substring(4,7), input.substring(7,11));
break;
case 12:
output = String.format("+%s (%s) %s-%s", input.substring(0,2) ,input.substring(2,5), input.substring(5,8), input.substring(8,12));
break;
default:
return null;
}
return output;
}

If you have the String "888-555-1234" - by using PhoneNumberUtils.formatNumber(numStr); you can simply do this:
String numStr = "888-555-1234";
numStr = "(" + numStr.substring(0,3) + ") " + numStr.substring(4);
System.out.print(numStr); // (888) 555-1234
However, this is hard coded. You would need to make sure the String had a full 10 digits before doing so.

You simply use this and get you want :
new PhoneNumberFormattingTextWatcher()
or Have look at this url :
http://developer.android.com/reference/android/telephony/PhoneNumberFormattingTextWatcher.html

Try to use regex. This will help you. As for me, i use this:
var result = "+1 888-555-1234"
if (Pattern.compile("^\\+[\\d]+\\s[\\d]{1,3}\\s[\\d]+").matcher(result).find()) {
result = result.replaceFirst(" ", "(").replaceFirst(" ", ")").replace(" ","-")
}
if(Pattern.compile("^\\+[\\d]+\\s[\\d]{1,3}-[\\d]+").matcher(result).find()){
result = result.replaceFirst(" ", "(").replaceFirst("-", ")")
}
Timber.d("$result")
output: +1(888)555-1234

Working solution in 2020:
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String countryIso = telephonyManager.getNetworkCountryIso().toUpperCase();
phoneNumberTextView.setText(PhoneNumberUtils.formatNumber("3473214567", countryIso));

Related

regex skips the first match

The regex
.*([0-9]{3}\\.[0-9]{2}).*
finds one match in "some short sentence 111.01 ", but it failed to match the first occurrence "111.01" in "some short sentence 111.01 & 222.02 "
I tried the lazy quantifier .*([0-9]{3}\\.[0-9]{2})?.* or .*([0-9]{3}\\.[0-9]{2}).*? for no avail.
Please help, I need to get both occurrences, here is my code.
Thank you
Pattern myPattern = Pattern.compile(".*([0-9]{3}\\.[0-9]{2}).*");
Matcher m = myPattern.matcher(mystring);
while (m.find()) {
String found = m.group(1);
}
you need to remove ".*"s. Try this:
String mystring = "some short sentence 111.01 & 222.02 ";
Pattern myPattern = Pattern.compile("([0-9]{3}\\.[0-9]{2})");
Matcher m = myPattern.matcher(mystring);
while(m.find()) {
System.out.println("Found value: " + m.group(1) );
}
output:
Found value: 111.01
Found value: 222.02
The leading and trailing ".*" cause you to match the entire string in one match. All the lazy quantifier does in your case is controls you getting the first, not last, occurrence in the subject.

Exctract values from given text in android

I am trying to extract values from a given text.
Here is the text:
String 1: $.675.00 was spent on your CAPITAL ONE CREDIT Card ending 2123 on 2015-05-04:15:28:08 at Best Buy
String 2: $ 1,310.00 was spent on your Credit Card 5178XXXXXXXX6040 on MAY-04-15 at Amazon Stores.
I want to extract the following from string:
Amount after $
Credit Card text
Credit card number (in this case - 2123 or 5178XXXXXXXX6040)
at which place (in this case Best Buy or Amazon Stores).
To start I was trying extract all the numbers from the string: I tried the following:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(string1);
Log.e("Value","from String"+m.group(0));
I am always getting the following error:
05-05 10:09:35.532: E/AndroidRuntime(13618): java.lang.IllegalStateException: No successful match so far
05-05 10:09:35.532: E/AndroidRuntime(13618): at java.util.regex.Matcher.ensureMatch(Matcher.java:471)
05-05 10:09:35.532: E/AndroidRuntime(13618): at java.util.regex.Matcher.group(Matcher.java:578)
Why isn't it matching even though the text has numbers?
Thanks!
As #justhecuke told there is no strict format for your string values to split using Patterns so I did using String functions, give a try
String crType1 = "CREDIT Card ending ";//mind the space at end
String crType2 = "Credit Card ";//mind the space at end
String rate, cardNo, at;
if (string1.contains(crType1)) {
rate = getStringValue(string1, "$", " ");
cardNo = getStringValue(string1, crType1, " ");
at = getAddress(string1);
} else {
rate = getStringValue(string1, "$", " ");
cardNo = getStringValue(string1, crType2, " ");
at = getAddress(string1);
}
System.out.println(String.format("Rate : %s Card No : %s Address : %s", rate, cardNo, at));
Methods
public static String getAddress(String string) {
return string.substring(string.lastIndexOf("at") + 2, string.length()).trim();
}
public static String getStringValue(String string, String startString, String endString) {
int startAt = string.indexOf(startString) + startString.length();
int endAt = string.indexOf(endString, startAt);
return string.substring(startAt, endAt).trim();
}
By the time you call m.group(0) you haven't actually told it to try to match stuff yet. This is why it gives you an IllegalStateException.
Try:
while(m.find()) {
Log.e("Value",String.format("From String: '%s'", m.group()));
}

how to get text with using substring

I try to get only this part "9916-4203" in "Region Code:9916-4203 " in android. How can I do this?
I tried below code, I used substring method but it doesn't work:
firstNumber = Integer.parseInt(message.substring(11, 19));
If you know that string contains "Region Code:" couldn't you do a replace?
message = message.replace("Region Code:", "");
Assumed that you have only one phone number in your String, the following will remove any non-digit characters and parse the resulting number:
public static int getNumber(String num){
String tmp = "";
for(int i=0;i<num.length();i++){
if(Character.isDigit(num.charAt(i)))
tmp += num.charAt(i);
}
return Integer.parseInt(tmp);
}
Output in your case: 99164203
And as already mentioned, you won't be able to parse any String to Integer in case there are any non-digit characters
Im going to guess that what you want to extract is the full region code text minus the title. So maybe using regex would be a good simple fit for you?
String myString = "Region Code:9916-4203";
String match = "";
String pattern = "\:(.*)";
Pattern regEx = Pattern.compile(pattern);
Matcher m = regEx.matcher(myString);
// Find instance of pattern matches
Matcher m = regEx.matcher(myString);
if (m.find()) {
match = m.group(0);
}
Variable match will contain "9916-4203"
This should work for you.
Java code sourced from http://android-elements.blogspot.in/2011/04/regular-expressions-in-android.html
In Java the substring() method works with the first parameter being inclusive and the second parameter being exclusive. Meaning "Hello".substring(0, 2); will result in the string He.
In addition to excluding the parsing of something that isn't a number like #Opiatefuchs mentioned, your substring method should instead be message.substring(12, 21).

Determine phone number country code from local address book

I am allowing the user to choose a phone number from their address book. I need the number to always be in the international format, however sometimes people store a local number without the country code in their contacts (ex. 555-555-5555 instead of +1-555-555-5555).
Is there an easy way to find out what country code the local number implies so I can add it manually?
This is what you need
https://code.google.com/p/libphonenumber/
String numberString = "044 668 18 00"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber numberProto = phoneUtil.parse(numberString, "BH"); // Where BH is the user's iso country code
String finalNumber = phoneUtil.format(numberProto, PhoneNumberFormat.E164);
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}

Change value of R.string programmatically?

I'm looking for a way to change the value of a string resource dynamically. I have tried to use reflection but it claims 'invalid value for field'.
I use the strings for values within the layout, but need to swap them out for different languages.
Please see the attached code below.
public class Lang{
public static void langInit(){
java.lang.reflect.Field[] langStringFields = R.string.class.getFields();
Log.d(Global.TAG,"--> Lang Listing: " + langStringFields.length);
Log.d(Global.TAG,"--> Pref for language:");
String prefInLang = Prefs.cPrefsGet.getString("in_lang","en");
String fieldName = null;
String fieldValue = null;
String newFieldName = null;
String tmpA = "one";
for (int i=0; i<langStringFields.length; i++){
java.lang.reflect.Field field = langStringFields[i];
fieldName = field.getName();
try {
fieldValue = Global.gActivity.getString(field.getInt(R.string.class));
} catch (Exception e) {
e.printStackTrace();
}
if (fieldName.substring(0,2).equals("lo")){
try {
newFieldName = R.string.class.getField(prefInLang + "_" + fieldName.substring(3)).getName();
} catch (Exception e) {
e.printStackTrace();
}
Log.d(Global.TAG,"--> Field: " + fieldName + "value: " + fieldValue + "new field:" + newFieldName);
try {
java.lang.reflect.Field field2 = Class.forName(R.string.class.getName()).getDeclaredField(newFieldName);
field2.setAccessible(true);
field2.set(R.string.class,tmpA.toString());
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Use built-in mechanism of localization, introduced in android. You don't need to change anything. You just need to specify the new strings.xml for each locale.
If you want to change current language for you app you can do it by using standard built-in localization features and changing locale programatically.
you should rather add a locale value to your resources and duplicate them : one for each language, thus letting the device choose the right one according to it's settings : check it there http://developer.android.com/resources/tutorials/localization/index.html
I believe using Android's built-in localization features is preferable to implementing it by hand. Here's a guide you can refer to:
http://developer.android.com/guide/topics/resources/localization.html
Unless, of course, we misunderstood your use case, but it does really sound like you are trying to do standard localization :-)
Bruno Oliveira, Developer Programs Engineer, Google

Categories

Resources