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.
Related
Background
It is possible to check if a given string represents a valid phone number, using this code, together with the PhoneNumberUtil library by Google (available here) :
public static boolean isValidNumber(final PhoneNumber phone) {
if (phone == null)
return false;
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
return phoneNumberUtil.isValidNumber(phone);
}
public static boolean isValidPhoneNumber(String phone) {
if (TextUtils.isEmpty(phone))
return false;
phone = phone.replaceAll("[^0-9]", "");
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
PhoneNumber phoneNumber = null;
try {
phoneNumber = phoneNumberUtil.parse(phone, Locale.getDefault().getCountry());
} catch (final Exception e) {
}
return isValidNumber(phoneNumber);
}
The problem
This is only a general check, but I can't find out if it's possible to know if the phone number is actually of a mobile device.
What I've tried
As I've read in some websites, the above check might need to have just a small adjustment to know if it's of a mobile device, but according to my tests, it's wrong :
...
phone = phone.replaceAll("[^0-9]", "");
if (phone.length() < 7)
return false;
...
The question
Is it possible to know if the phone number is of a mobile device?
If so, how ?
Seems I've missed the function in the library. Here's how to do it:
public static boolean isValidMobileNumber(String phone) {
if (TextUtils.isEmpty(phone))
return false;
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber phoneNumber = phoneNumberUtil.parse(phone, Locale.getDefault().getCountry());
PhoneNumberUtil.PhoneNumberType phoneNumberType = phoneNumberUtil.getNumberType(phoneNumber);
return phoneNumberType == PhoneNumberUtil.PhoneNumberType.MOBILE;
} catch (final Exception e) {
}
return false;
}
EDIT: it seems some numbers (in the US and a few others ) cannot be determined whether they are of mobile phones or not. In this case, FIXED_LINE_OR_MOBILE is returned.
If you still need to know if the phone number is mobile, there are online services to check it out (though they can't know all, of course), such as Pathfinder.
This is the mobile phone validation for Turkey. You can arrange the regex as your country.You can check the algorithm from Wikipedia
public static boolean validateMobilePhone(String phone) {
String regEx = "(^(\\+905)|^(905)|^(05)|^(5))((01)|(05)|(06)|(07)|(51)|(52)|
(53)|(54)|(55)|(59)|(30)|(31)|(32)|(33)|(34)|(35)|(36)|(37)|(38)|(39)|(61)|
(40)|(41)|(42)|(43)|(44)|(45)|(46)|(47)|(48)|(49))(\\d{7})$";
return Pattern.compile(regEx).matcher(phone).matches();
}
you can do it if you want for one country regular expression
private boolean isValidNumber(String phonenumber) {
String PHONE_PATTERN = "^(984|986)\\d{7}$";
// phone number starts with 984 and 986 and has 7 digit after that ex: 9842248633 (true or valid) and 9851048633(false or not valid) and in total 10 digits number
Pattern pattern = Pattern.compile(PHONE_PATTERN);
Matcher matcher = pattern.matcher(phonenumber);
return matcher.matches();
}
And you can call this function like this:
phoneNumber.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!isValidNumber(s.toString())){
isnumbervalid=false;
phoneNumber.setTextColor(Color.parseColor("#F44336"));
}else {
isnumbervalid=true;
phoneNumber.setTextColor(Color.parseColor("#000000"));
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
And further more you can also limit android:maxlength=10; in edit text to not let user enter number with lenght greater than 10
If you need for Country or Locale basis then you can use this using Google phonenumber library.
Dependency for this library if you are using gradel
compile 'com.googlecode.libphonenumber:libphonenumber:7.1.1'
String nepalNumberStr = "9842248633";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
TelephonyManager tm = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE); // for device containing sim card
String locale = tm.getNetworkCountryIso();// for device containing sim card
// Else you need to access locale through GPS
try {
Phonenumber.PhoneNumber nepalNumber = phoneUtil.parse(nepalNumberStr, locale.toUpperCase());
boolean isValid = phoneUtil.isValidNumber(nepalNumber); // returns true
if(isValid) {
String internationally = phoneUtil.format(nepalNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
Toast.makeText(this, nepalNumberStr + " is " + isValid + " and number is :" + internationally + "And is "+ phoneUtil.getNumberType(nepalNumber), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "This phone number is not valid for " + locale, Toast.LENGTH_SHORT).show();
}
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
OK please Check this line out for MOBILE or FIXED_LINE
phoneUtil.getNumberType(nepalNumber)
I am trying to make somekind of version checker for my application.
The idea is to compare the numbers from 2 strings and if 1 set of numbers is bigger then the other a new version has been found.
oldString = 360 some - File v1.52.876 [build 2546]
newString = 360 some - File v1.53.421 [build 2687]
What I need is to compare the set numbers after the 'v' in both strings as there can also be numbers (360) in front of the file, as shown in above example.
Below method checks an arraylist (loadTrackedItems) which contains the files to be checked agains the newly received item (checkItemTrack).
But I am having trouble getting the correct numbers.
Is there a better way to do this?, could somebody be so kind and help a bit.
Thank you in advance.
public static boolean newTrackedVersion(String checkItemTrack) {
final List<String> tracking = new ArrayList<String>(loadTrackedItems);
boolean supported = false;
for (final String u : tracking) {
if (checkItemTrack.contains(u)) {
supported = true;
// get the index of the last 'v' character
int trackindex = checkItemTrack.lastIndexOf("v");
String newItem = checkItemTrack.replaceAll("[a-zA-Z]", "").replace("\\s+", "")
.replaceAll("[-\\[\\]^/,'*:.!><~##$%+=?|\"\\\\()]+", "");
String inList = u.replaceAll("[a-zA-Z]", "").replace("\\s+", "")
.replaceAll("[-\\[\\]^/,'*:.!><~##$%+=?|\"\\\\()]+", "");
long newTrack = Long.parseLong(newItem.trim());
long inTrackList = Long.parseLong(inList.trim());
if (newTrack > inTrackList) {
//Toast.makeText(context,"New version found: " + checkItemTrack, Toast.LENGTH_LONG).show();
Log.w("NEW VERSION ", checkItemTrack);
Log.w("OLD VERSION ", u);
}
break;
}
}
return supported;
}
if you receive only two strings to compare this solution will work try it.
String oldString = "360 some - File v1.52.876 [build 2546]";
String newString = "360 some - File v1.53.421 [build 2687]";
String oldTemp = oldString.substring(oldString.indexOf('v'), oldString.indexOf('[')).trim();
String newTemp = newString.substring(newString.indexOf('v'), newString.indexOf('[')).trim();
int res = newTemp.compareTo(oldTemp);
if(res == 1){
//newString is higher
}else if(res == 0){
//both are same
}else if(res == -1){
//oldString is higher
}
I am developing a mobile application in android.The application gets data from a database(in SQL Server) using a soap web service(in java). Now i have been stuck into a problem and it is as follows- the android application retrieves a row (all the columns) from the database and sets the column values to the respective text fields but i don't know what to do in the web service. Please help me
My Code for the web method is-
#WebMethod(operationName = "DiseaseInfoGC")
public String DiseaseInfo4( #WebParam(name = "crop_name") String crop,
#WebParam(name = "spread_mode") String spread_mode,
#WebParam(name = "path_cong_env") String path_cong_env) {
query_disease = new String();
try {
DBConnect.databaseconnect();
Statement stmt_disease = DBConnect.connect.createStatement();
query_disease = "Select * from Disease where crop_name='" + crop + "' and Disease_SpreadMode='"+spread_mode+"' "
+ "and Disease_PathCongEnv='" + path_cong_env + "'";
System.out.println(query_disease);
ResultSet rslt_disease = stmt_disease.executeQuery(query_disease);
System.out.println(query_disease);
executemyquery(rslt_disease);
System.out.println(query_disease);
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (SQLException ex) {
System.out.println(ex.getMessage());;
} catch (NullPointerException ex) {
System.out.println(ex.getMessage());
}
return disease_name;
}
And the executequery() is-
private void executemyquery(ResultSet rslt_disease) throws SQLException {
while (rslt_disease.next()) {
disease_name = rslt_disease.getString("Disease_EngName");
System.out.println("Name Of the Disease: "+disease_name);
path_name = rslt_disease.getString("Disease_PathScName");
System.out.println("Name of the Pathogen: "+path_name);
path_geo_dis = rslt_disease.getString("Disease_PathGeoDist");
System.out.println("Pathogen Scientific name: "+path_geo_dis);
path_life_cycle = rslt_disease.getString("Disease_PathLCycle");
System.out.println("Life Cycle of the Pathogen: "+path_life_cycle);
disease_symptoms = rslt_disease.getString("Disease_Symptom");
System.out.println("Disease Symptoms: "+disease_symptoms);
disease_controls = rslt_disease.getString("Disease_Control");
System.out.println("Disease control mechanism: "+disease_controls);
prevention = rslt_disease.getString("Disease_Prevention");
System.out.println("Disease prevention Mechanism: "+prevention);
spread_mode = rslt_disease.getString("Disease_SpreadMode");
System.out.println("Spread mode of the disease: "+spread_mode);
primary_source = rslt_disease.getString("Disease_PSource");
System.out.println("Primary Source: "+primary_source);
secondary_source = rslt_disease.getString("Disease_SSource");
System.out.println("Secondary Source: "+secondary_source);
path_a_host = rslt_disease.getString("Disease_PathAHost");
System.out.println("Pathogen host"+path_a_host);
path_cong_env = rslt_disease.getString("Disease_PathCongEnv");
System.out.println("Pathogen Congenial Envoronment"+path_cong_env);
occur_period = rslt_disease.getString("Disease_OccurancePd");
System.out.println("Disease occuring period: "+occur_period);
}
I have just stored the column values in the string. I know that it is useless use string here. But i have no idea how to store the column values from the database in the web method so that i can use them in the android application.Hope you can understand my question. Please guide me..
I am trying to validate my mobile number which I am picking up from Contac List but the problem is that it is picking contact like +91 95 xx xxxxxx and there is space between numbers so the validation is not happening.
For now I am using this validation
String Mobile = "^[+]?[01]?[- .]?(\\([2-]\\d{2}\\)|[2-9]\\d{2})[- .]?\\d{3}[- .]?\\d{4}$";
But it's a failure.
Any help is appreciable.
Thank you.
In android sdk One class is there PhoneNumberUtils by using that class you can validate your phone number:
check the documentation link here
Replace the spaces then validate..
String phone=phone.replace(" ","");
Now the String phone has the text without spaces and you can compare.
Just try this.
String number = " " //Your mobile number
number.replaceAll("[^+\\d]|(?<=.)\\+", ""));
This will remove all the spaces, (, ) symbols
you can use below code :
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
try
{
if (phoneNumber != null)
phoneNumber = extractDigits(phoneNumber);
}
catch (Exception e)
{
e.printStackTrace();
}
where extractDigits() method is as :
public static String extractDigits(String src)
{
StringBuilder builder = new StringBuilder();
String firstchar = src.substring(0, 1);
for (int i = 0; i < src.length(); i++)
{
char c = src.charAt(i);
if (Character.isDigit(c) || firstchar.equals("+"))
{
firstchar = "";
builder.append(c);
}
}
return Checkvalidnumber(builder.toString());
}
where Checkvalidnumber() method is as :
public static String Checkvalidnumber(String number)
{
String validnumber = "";
String Countrycode = chatPrefs.getString("countryCode", "");
if (number.startsWith("+"))
{
validnumber = number.trim();
}
else if (number.startsWith("0"))
{
validnumber = (Countrycode + number.substring(1, number.length())).trim();
}
else
{
validnumber = (Countrycode + number).trim();
}
return validnumber;
}
You should try the following to remove the white spaces and then you can do the validation.
var str = "PB 10 CV 2662";
str = str.replace(/ +/g, "");
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