Below code...
#GetMapping("/brian/{number}")
public String getBrianMessage(#PathVariable int number) throws NumberFormatException {
try {
logList.add(number);
String stringList = logList.toString();
return "List is " + stringList;
} catch (NumberFormatException e){
int newCount= 999;
logList.add(newCount);
String stringList = logList.toString();
return "List is " + stringList;
}
}
When going to the url i would like the integer stored in a list. This works fine when you use a valid integer value. I want the ability to default the value to 999 when a string is supplied. So, if i go to /brian/string it should add 999 to the list and return it. This is not working and I'm getting the same error as before I added the exception handling
I have doubt in that section. How to Remove country code, when I pick phone number from contact list?
Ex: +91 999999999 instead of 9999999999 or +020 9696854549 instead of 9696854549 Can any one know the answer about my question. please give solution to this problem
I attached my code and image here.
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null ;
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
// column index of the phone number
int phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER
phoneNo = cursor.getString(phoneIndex);
String phoneNumber = phoneNo.replaceAll(" ","");
mobile_et.setText(phoneNumber);
} catch (Exception e) {
e.printStackTrace();
}
}
You can use startsWith()
This method has two variants and tests if a string starts with the
specified prefix beginning a specified index or by default at the
beginning.
if(phoneNumber.startsWith("+"))
{
if(phoneNumber.length()==13)
{
String str_getMOBILE=phoneNumber.substring(3);
mobile_et.setText(str_getMOBILE);
}
else if(phoneNumber.length()==14)
{
String str_getMOBILE=phoneNumber.substring(4);
mobile_et.setText(str_getMOBILE);
}
}
else
{
mobile_et.setText(phoneNumber);
}
My English is poor, but I will try my best to answer your question.
First of all , add this line to your build.gradle
compile 'com.googlecode.libphonenumber:libphonenumber:8.7.0'
And below is a sample write by kotlin
fun deleteCountry(phone: String) : String{
val phoneInstance = PhoneNumberUtil.getInstance()
try {
val phoneNumber = phoneInstance.parse(phone, null)
return phoneNumber?.nationalNumber?.toString()?:phone
}catch (_ : Exception) {
}
return phone
}
If phone number not start with a '+' followed by the country calling code then you should pass region information, for example:
val phoneNumber = phoneInstance.parse(phone, "CN")
Try this....
if(number.length()>10)
{
int startidx=number.length()-10;
String getnumber=number.substring(startidx,number.length());
etEmerNumber.setText(getnumber);
}
else
{
etEmerNumber.setText(number);
}
I am just simply extending the answer that If you don't want to use any library then you can do it in this way. In order to match any prefix and since some countries could share partially the same prefix (for example 91 and 91-721), you add all possibilities to the regex in descending order and size.
Follow this Code:
public static String PhoneNumberWithoutCountryCode(String phoneNumberWithCountryCode){//+91 7698989898
Pattern compile = Pattern.compile("\\+(?:998|996|995|994|993|992|977|976|975|974|973|972|971|970|968|967|966|965|964|963|962|961|960|886|880|856|855|853|852|850|692|691|690|689|688|687|686|685|683|682|681|680|679|678|677|676|675|674|673|672|670|599|598|597|595|593|592|591|590|509|508|507|506|505|504|503|502|501|500|423|421|420|389|387|386|385|383|382|381|380|379|378|377|376|375|374|373|372|371|370|359|358|357|356|355|354|353|352|351|350|299|298|297|291|290|269|268|267|266|265|264|263|262|261|260|258|257|256|255|254|253|252|251|250|249|248|246|245|244|243|242|241|240|239|238|237|236|235|234|233|232|231|230|229|228|227|226|225|224|223|222|221|220|218|216|213|212|211|98|95|94|93|92|91|90|86|84|82|81|66|65|64|63|62|61|60|58|57|56|55|54|53|52|51|49|48|47|46|45|44\\D?1624|44\\D?1534|44\\D?1481|44|43|41|40|39|36|34|33|32|31|30|27|20|7|1\\D?939|1\\D?876|1\\D?869|1\\D?868|1\\D?849|1\\D?829|1\\D?809|1\\D?787|1\\D?784|1\\D?767|1\\D?758|1\\D?721|1\\D?684|1\\D?671|1\\D?670|1\\D?664|1\\D?649|1\\D?473|1\\D?441|1\\D?345|1\\D?340|1\\D?284|1\\D?268|1\\D?264|1\\D?246|1\\D?242|1)\\D?");
String number = phoneNumberWithCountryCode.replaceAll(compile.pattern(), "");
//Log.e(tag, "number::_>" + number);//OutPut::7698989898
return number;
}
It will work for all instances. You need not care about how much digit the country code is
String get_Mo = phoneNumber.substring(phoneNumber.lastIndexOf(' ')+1));
If you can use a library, this might help you:
Gradle:
repositories {
mavenCentral()
}
dependencies {
implementation 'io.michaelrocks:libphonenumber-android:8.12.51'
}
Java:
String getPhoneNummberWithoutCountryCode(String phoneNo)
{
PhoneNumberUtil phoneInstance = PhoneNumberUtil.createInstance(this.getContext());
Phonenumber.PhoneNumber phoneNumber = phoneInstance.parse(phoneNo, null);
String nationalSignificantNumber = phoneInstance.getNationalSignificantNumber(phoneNumber);
return nationalSignificantNumber;
}
nationalSignificantNumber is the required phone number
use this function hope it will help you out:
public String phoeNumberWithOutCountryCode(String phoneNumberWithCountryCode) {
Pattern complie = Pattern.compile(" ");
String[] phonenUmber = complie.split(phoneNumberWithCountryCode);
Log.e("number is", phonenUmber[1]);
return phonenUmber[1];
}
String Trimmed = s.toString().trim();
if(Trimmed.length() > 10){
char[] number = Trimmed.toCharArray();
int extra;
int dif = Trimmed.length() - 10 ;
for(int i = dif; i < Trimmed.length() ; i++){
extra = i-dif;
number[extra] = number[i];
}
for (int i = 10 ; i < Trimmed.length() ; i++){
number[i]=' ';
}
String finalNumber = String.valueOf(number);
MobileNumberET.setText(finalNumber.trim());
}
//paste this in your text change listener
Use a library
https://groups.google.com/forum/?hl=en&fromgroups#!forum/libphonenumber-discuss
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
// phone must begin with '+'
PhoneNumber numberProto = phoneUtil.parse(phone, "");
int countryCode = numberProto.getCountryCode();
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
If you'd like to perform some extra function on a particular Sim on the mobile you can use some of the many methods below.
Might not be a perfect solution but, I'll try my best.
First get the country code programmatically :
TelephonyManager tm = (TelephonyManager)
this.getSystemService(Context.TELEPHONY_SERVICE);
//get the country iso from sim e.g US, NG, FR etc
String countryIso = tm.getSimCountryIso().toUpperCase():
//get countrycode from refegion returns the code e.g +123, +1, +23 etc.
Int countryCode =
phoneNumberUtil.getInstance().getCountryCodeForRegion(countryIso);
Then you can remove it using your preferred way likeString PhoneNumber = phoneNo.replaceAll("countryCode ", "" );
First of all, make sure your given phone number should be in a Normalized format
like
+921234567
then use the libphonenumber google library, so, in build.gradle add this
implementation 'com.googlecode.libphonenumber:libphonenumber:8.13.4'
then follow the below code:
val phoneUtil = PhoneNumberUtil.getInstance()
try {
val phoneNumberProto: Phonenumber.PhoneNumber = phoneUtil.parse(number, null)
val numberWithoutCountryCode = phoneUtil.getNationalSignificantNumber(phoneNumberProto)
Log.d(Constant.LOG_APP_DEBUG, "PhoneNumber: $numberWithoutCountryCode")
} catch (e: NumberParseException) {
Log.d(Constant.LOG_APP_DEBUG, "NumberParseException was thrown: $e")
}
I have a Java object that contains a few String variables. When creating a json message from a Java object if one of the String values is alpha numeric, then the conversion will return back a quoted value. Else the conversion will return back a numeric value.
Example:
Class User {
String userid , password;
}
if userid = "tom" and password = "123456" then the JSON conversion returns back
"userid":"tom" and "password":123456 (numeric)
It should actually return "password":"123456"
How can I achieve this? I am using the Java parser from json.org and below is a snippet of code that converts the Java object to Json.
final JSONObject jsonObject = XML.toJSONObject(writer.toString());
res = jsonObject.toString(4);
It's because of stringToValue method in JSONObject.
It tries to guess a type.
It's open source so you can change it if you want.
Just return string.
/**
* Try to convert a string into a number, boolean, or null. If the string
* can't be converted, return the string.
*
* #param string
* A String.
* #return A simple JSON value.
*/
public static Object stringToValue(String string) {
if (string.equals("")) {
return string;
}
if (string.equalsIgnoreCase("true")) {
return Boolean.TRUE;
}
if (string.equalsIgnoreCase("false")) {
return Boolean.FALSE;
}
if (string.equalsIgnoreCase("null")) {
return JSONObject.NULL;
}
/*
* If it might be a number, try converting it. If a number cannot be
* produced, then the value will just be a string.
*/
char initial = string.charAt(0);
if ((initial >= '0' && initial <= '9') || initial == '-') {
try {
if (string.indexOf('.') > -1 || string.indexOf('e') > -1
|| string.indexOf('E') > -1
|| "-0".equals(string)) {
Double d = Double.valueOf(string);
if (!d.isInfinite() && !d.isNaN()) {
return d;
}
} else {
Long myLong = new Long(string);
if (string.equals(myLong.toString())) {
if (myLong.longValue() == myLong.intValue()) {
return Integer.valueOf(myLong.intValue());
}
return myLong;
}
}
} catch (Exception ignore) {
}
}
return string;
}
You could use staxon library instead: its JsonXMLConfigBuilder lets you control the behavior during conversion (such as autoprimitive which lets you define how you want to handle primitive values). Here's the code:
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><userid>tom</userid><password>123456</password></root>";
ByteArrayOutputStream bao = new ByteArrayOutputStream();
JsonXMLConfig config = new JsonXMLConfigBuilder().autoArray(true).autoPrimitive(false).prettyPrint(true).build();
try {
XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(IOUtils.toInputStream(xml));
XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(bao);
writer.add(reader);
reader.close();
writer.close();
} finally {
bao.close();
}
String json = bao.toString();
JsonXMLConfigBuilder()...autoPrimitive(false) does the trick you are looking for: the number fields are kept as Strings.
With this code sample, you need to add Saxion + commons-io (just for IOUtils.toInputStream(xml)) :
<dependency>
<groupId>de.odysseus.staxon</groupId>
<artifactId>staxon</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4<version>
</dependency>
Some documentation on staxon:
github
dzone
1)I need to check if String contains a String characters what will be the corect way how to do it ?
2) Are some ways how to corectly transform String to number and then compare theese two number s? Like String = "House":1234 is equal to "House":1234 but no to "house":123
Priview:
String token ="123"; False
String token = "ā123"; or other characters True utc.
if(isChars(token)){
Long value = toLong(token);
}
THANKS!
//EDIT
public BigDecimal eval() {
Stack<BigDecimal> stack = new Stack<BigDecimal>();
for (String token : getRPN()) {
if (operators.containsKey(token)) {
BigDecimal v1 = stack.pop();
BigDecimal v2 = stack.pop();
stack.push(operators.get(token).eval(v2, v1));
} else if (variables.containsKey(token)) {
stack.push(variables.get(token).round(mc));
} else if (functions.containsKey(token.toUpperCase())) {
Function f = functions.get(token.toUpperCase());
ArrayList<BigDecimal> p = new ArrayList<BigDecimal>(f.getNumParams());
for (int i = 0; i < f.numParams; i++) {
p.add(0, stack.pop());
}
BigDecimal fResult = f.eval(p);
stack.push(fResult);
} else if (isDate(token)) {
Long date = null;
try {
date = SU.sdf.parse(token).getTime();
} catch (ParseException e) {/* IGNORE! */
}
// mylog.pl("LONG DATE : "+new BigDecimal(date, mc));
stack.push(new BigDecimal(date, mc));
}//TODO HERE
else if (isChar(token)){
Long cha = toLong(token);
stack.push(new BigDecimal(cha, mc));
//TODO ENDS HERE
}
else {
// mylog.pl("Token : "+ token);
stack.push(new BigDecimal(token, mc));
}
}
return stack.pop().stripTrailingZeros();
}
Another way for determing whether string contains any chars is nice class StringUtils from apache-commons-lang library.
It contains several methods for analyzing string's contents. It seems that in your case you can use StringUtils.isAlphanumeric(CharSequence cs) or negation of StringUtils.isNumeric(CharSequence cs)'s result.
What about second part of your question, so I do not see here necessety of extracting numbers from string. You can compare strings "House":1234 and "house":123 using standard String.equals() method.
Long l;
try{
l = Long.parseLong(token);
} catch(NumberFormatException e){
//contains non-numeric character(s)
}
As for "transforming varchar into Long" - that sounds rather impossible, we do not have universally accepted way of doing that, and you did not provide one. However if I guess correctly that what you want is the number within the string disregarding the characters - you want regular expressions. The code you want could look like:
if (!StringUtils.isNumeric(token)){
String stripped = token.replaceAll("\\D","");
Long l = Long.parseLong(stripped);
}
I can't change the EditTextPreference value from string to int. I've done in this way:
WifiOnOffValue = (EditTextPreference) findPreference("WifiOnOffValue");
String value = WifiOnOffValue.getText().toString();
if(value != null && !value.isEmpty()) {
try {
vedit = Integer.parseInt(value);
}
catch (NumberFormatException ex) {
ex.printStackTrace();
vedit = 0;
}
}
And I get the error java.lang.Integer cannot be cast to java lang.String... I need convert the value of my EditTextPreference in integer. Thanks
Log:
Code:
//-- Edittext Wifi
WifiOnOffValue = (EditTextPreference) findPreference("WifiOnOffValue");
String value = WifiOnOffValue.getText().toString().trim();
if(value!=null && !value.isEmpty()){
try{
vedit = Integer.parseInt(value);
} catch (NumberFormatException ex) {
ex.printStackTrace();
vedit=0;
}
}
Solved.. this was the solution: ClassCastException in PreferenceActivity seems that it stored wrong values.. Now i can start the app and seems goes well.. The solution to me was simply uninstall and reinstall the application.. so strange. Thanks to everybody anyway
Could you check the type of variable vedit? Is wrongly declared as String?
try to use String value = WifiOnOffValue.getText().toString().trim() and log out to see what the value of value is
Should'nt it be
WifiOnOffValue = (EditTextPreference) getPreferenceManager().findPreference("WifiOnOffValue");