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")
}
Related
I'm making an iOS app that parses JSON data from a google spreadsheet. One of the issues with Google JSON data is that it includes unnecessary data that has to be removed. I'm new to iOS programming.
/*O_o*/google.visualization.Query.setResponse({"version":"0.6","reqId":"0","status":"ok","sig":"1400846503","table":{JSON DATA I NEED}});
I have done this in JAVA on Android using this code
int start = result.indexOf("{", result.indexOf("{") + 1);
int end = result.lastIndexOf("}");
String jsonResponse = result.substring(start, end);
My swift code
var something = "My google JSON Data"
let Start = String(something).characters.indexOf("{")!;
let substring1: String = something.substringFromIndex(Start);
something = substring1;
let End = String(something).characters.indexOf(")")!.distanceTo(something.endIndex);
let index3 = something.endIndex.advancedBy(-End);
let substring4: String = something.substringToIndex(index3)
What I'm asking is how do I get the index of the 2nd "{"
You should use NSJsonSerializer, but if you want to do it your way:
extension String {
func indexOf(target: String) -> Int {
if let range = self.rangeOfString(target) {
return self.startIndex.distanceTo(range.startIndex)
} else {
return -1
}
}
func indexOf(target: String, startIndex: Int) -> Int {
let startRange = self.startIndex.advancedBy(startIndex)
if let range = self.rangeOfString(target, options: .LiteralSearch, range: startRange..<self.endIndex) {
return self.startIndex.distanceTo(range.startIndex)
} else {
return -1
}
}
}
let end = myString.indexOf("{", startIndex: myString.indexOf("{") + 1)
I'm working with JavaEE i need to convert this: request.getParameter("id") to int. The value of request.getParameter("id") is "9" (String).
When I'm trying to convert to int I have
java.lang.NumberFormatException
I've tried java.lang.Integer.parseInt(request.getParameter("id")) and request.getParameter("id",10) but it donsen't works...
Any solutions? Thank you.
A complete full proof code would be
String idString = request.getParameter("id");
if(idString != null) {
try {
System.out.println(idString.trim()); // print to verify
int idInt = Integer.parseInt(idString.trim());
}
catch(NumberFormatException nbe) {
nbe.printStackTrace();
}
}
First you need to check whether String returned by getParameter() is null or not then check whether it is empty ("") String or not then use Integer.parseInt().
String id = request.getParameter("id");
if(null != id && !("".equals(id))) {
try {
int number = Integer.parseInt(id.trim());
}
catch(NumberFormatException e) {
e.printStackTrace();
}
}
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 have a String containing a URL. I want to get just one piece of data out of it: an int that should be showing up in the query string.
So if the url is:
http://domain.tld/page.html?iVar=123
I want to get "123" into an int.
What's the most elegant way you know to do this?
You could try matching just that parameter in the URL string:
public static Integer getIVarParamValue(String urlStr) {
Pattern p = Pattern.compile("iVar=(\\d+)");
Matcher m = p.matcher(urlStr);
if (m.find()) {
return Integer.parseInt(m.group(1));
}
return null;
}
It seems you want to obtain get parameters and parse them. I have this method here (got it from somewhere on SO, I guess):
public static Map<String, List<String>> getQueryParams(String url) {
try {
Map<String, List<String>> params = new HashMap<String, List<String>>();
String[] urlParts = url.split("\\?");
if (urlParts.length > 1) {
String query = urlParts[1];
for (String param : query.split("&")) {
String[] pair = param.split("=");
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = "";
if (pair.length > 1) {
value = URLDecoder.decode(pair[1], "UTF-8");
}
List<String> values = params.get(key);
if (values == null) {
values = new ArrayList<String>();
params.put(key, values);
}
values.add(value);
}
}
return params;
} catch (UnsupportedEncodingException ex) {
throw new AssertionError(ex);
}
}
So:
String var = WebUtils.getQueryParams(url).get("iVar");
int intVar = Integer.parseInt(var);
You can use the URL class.
i.e.:
URL myUrl = new URL("http://domain.tld/page.html?iVar=123");
String query = myUrl.getQuery(); //this will return iVar=123
//at this point you can either parse it manually (i.e. use some of the regexp in the other suggestions, or use something like:
String[] parts = query.split();
String variable = parts[0];
String value = parts[1];
This will work only for this case though and won't work if you have additional params or no params.
There are a number of solution that will split it into a param map online, you can see some here.
If it's really as simple as you describe: There is only 1 int in your URL and all you want is that int, I'd go for a regular expression. If it is actually more complicated see the other answers.
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher("http://domain.tld/page.html?iVar=123");
if (m.find())
System.out.println(m.group());
This also could do the work :
public static int getIntParam(HttpServletRequest request, String name, int defaultValue) {
String value = request.getParameter(name);
try {
if (value != null) {
return Integer.valueOf(value);
}
} catch (NumberFormatException e) {
}
return defaultValue;
}
Hope it helps!
If the query string part of the URL is always the same (so if it was always iVar) you could use urlAsString.indexOf("iVar=") to find iVar= and then knowing the number is after that, extract the number. That is admittedly not the least brittle approach.
But if you're looking for all the query strings then Bozho's answer is much better.
I am new to eclipse plugin development and I am trying to convert a IMethod to a string representation of the full method name. I.E.
my.full.package.ClassName.methodName(int param, String string)
so far I have had to hand roll my own solution. Is there a better way?
private static String getMethodFullName(IMethod iMethod)
{
String packageString = "[Default Package]";
try {
IPackageDeclaration[] declarations = iMethod.getCompilationUnit().getPackageDeclarations();
if(declarations.length > 0)
{
packageString = declarations[0].getElementName();
}
} catch (JavaModelException e) {
}
String classString = iMethod.getCompilationUnit().getElementName();
classString = classString.replaceAll(".java", "");
String methodString = iMethod.getElementName() + "(";
for (String type : iMethod.getParameterTypes()) {
methodString += type + ",";
}
methodString += ")";
return packageString + "." + classString + "." + methodString;
}
You can get the Fully qualified name for the type using
method.getDeclaringType().getFullyQualifiedName();
This is probably easier than accessing the package from the compilation unit. The rest of you function looks correct.
One small point: you should use StringBuilder to build up the string instead of adding to a standard String. Strings are immutable so addition creates loads of unrecesary temparary objects.
private static String getMethodFullName(IMethod iMethod)
{
StringBuilder name = new StringBuilder();
name.append(iMethod.getDeclaringType().getFullyQualifiedName());
name.append(".");
name.append(iMethod.getElementName());
name.append("(");
String comma = "";
for (String type : iMethod.getParameterTypes()) {
name.append(comma);
comma = ", ";
name.append(type);
}
name.append(")");
return name.toString();
}
Thanks to iain and some more research I have come up with this solution. It seems like something like this should be built into the JDT....
import org.eclipse.jdt.core.Signature;
private static String getMethodFullName(IMethod iMethod)
{
StringBuilder name = new StringBuilder();
name.append(iMethod.getDeclaringType().getFullyQualifiedName());
name.append(".");
name.append(iMethod.getElementName());
name.append("(");
String comma = "";
String[] parameterTypes = iMethod.getParameterTypes();
try {
String[] parameterNames = iMethod.getParameterNames();
for (int i=0; i<iMethod.getParameterTypes().length; ++i) {
name.append(comma);
name.append(Signature.toString(parameterTypes[i]));
name.append(" ");
name.append(parameterNames[i]);
comma = ", ";
}
} catch (JavaModelException e) {
}
name.append(")");
return name.toString();
}
I am not sure it would take into account all cases (method within an internal class, an anonymous class, with generic parameters...)
When it comes to methods signatures, the classes to look into are:
org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedMethodsOperation
org.eclipse.jdt.internal.corext.codemanipulation.StubUtility2
You need to get the jdt.core.dom.IMethodBinding, from which you can extract all what you need.
If you have a MethodInvocation, you can:
//MethodInvocation node
ITypeBinding type = node.getExpression().resolveTypeBinding();
IMethodBinding method=node.resolveMethodBinding();