Android - Check content of a String - android

I have a string (length 3-8) assigned to a variable (text). I want to check whether the 2nd and 3rd characters are NOT numeric (a letter or symbol or space..or anything other than numbers).

Elementary way to do this could be:
if(((text.charAt(1)-'0')>=0)&&(text.charAt(1)-'0')<10))||((text.charAt(2)-'0')>=0)&&(text.charAt(2)-'0')<10)))
{
//do nothing, since this means 2nd and/or 3rd characters in the string are numeric
}
else
{
// Your condition is met
}
You could also use REGEX's , if your checking is still more complicated.

Here is Another way to achieve this:
boolean isNumeric = true;
String test = "testing";
char second = test.charAt(1);
char third = test.charAt(2);
try {
Integer.parseInt(String.valueOf(second));
Integer.parseInt(String.valueOf(third));
} catch(NumberFormatException e) {
isNumeric = false;
}
System.out.println("Contains Number in 2nd and 3rd or both position: " + isNumeric);

You might make use of the String.IndexOf(String) method, like:
String digits = "0123456789";
String s2 = text.substring(2,3);
String s3 = text.substring(3,4);
boolean valid = (digits.indexOf(s2) > -1) && (digits.indexOf(s3) > -1);

Related

Android : replacing characters in a string

In my phonebook on my mobile I have all sorts of contacts like :
+(353) 085 123 45 67
00661234567
0871234567
(045)123456
I'm putting them all into E.164 format which I've largely completed but the question I need resolved is this:
How can I strip all characters (including spaces) except numbers in my string, apart from the first character if it is '+' or a number ?
string phoneNumberofContact;
So for example the cases above would look like :
+3530851234567
00661234567
0871234567
045123456
Update
To handle + only in the first position, you could do:
boolean starsWithPlus = input.charAt(0) == '+';
String sanitized = input.replaceAll("[^0-9]", "");
if (startsWithPlus) {
sanitized = "+" + sanitized;
}
So basically I'm checking to see if it starts with plus, then stripping out everything but digits, and then re-adding the plus if it was there.
Original
Assuming you only want to keep + or digits, a simple regex will work, and String provides the replaceAll() method to make it even easier.
String sanitized = input.replaceAll("[^+0-9]", "");
This method would do the trick
public String cleanPhoneDigits(String phonenum) {
StringBuilder builder = new StringBuilder();
if (phonenum.charAt(0).equals('+') {
builder.append('+');
}
for (int i = 1; i < phonenum.length(); i++) {
char c = phonenum.charAt(i);
if (Character.isDigit(c)) {
builder.append(c);
}
}
return builder.toString();
}

Compare a set of numbers in string

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
}

How to detect if a string contains a specific Word

I have this code :
if (currentLocation.distanceTo(myModel.getNearest()) < 900) {
if (said != true) {
String seriousWarning = (myModel.getNearest().getProvider());
tts.speak(seriousWarning, TextToSpeech.QUEUE_ADD, null);
said = true;
warningTxt.setTextColor(Color.RED);
}
I would like to check if there a certain word in the seriousWarning string, knowing that (myModel.getNearest().getProvider()) is the title of the nearest GPS point to the device.
Any help would be much appreciated!
try below piece of code:
boolean isPdf = stringValue.matches(".*\\b"STRING_NAME"\\b.*");
You can use contains() method.
if(seriousWarning.contains("certainword"))
{
//Do something
}
You can use regular expressions to check if a string contains a substring.
This code snippet is from the android developer documentation.
// String convenience methods:
boolean sawFailures = s.matches("Failures: \\d+");
String farewell = s.replaceAll("Hello, (\\S+)", "Goodbye, $1");
String[] fields = s.split(":");
// Direct use of Pattern:
Pattern p = Pattern.compile("Hello, (\\S+)");
Matcher m = p.matcher(inputString);
while (m.find()) { // Find each match in turn; String can't do this.
String name = m.group(1); // Access a submatch group; String can't do this.
use indexOf("String to be checkecked");
if(seriousWarning.indexOf("String to be checkecked") > -1)
{
// your code
}

Android compare string ignore case

resultString is the parameter I get from sqlite
resultString = result.getString(result.getColumnIndex(1));
I want to compare ignore case with user input , following is the code I have use. But it doesn't work.
For example, in database, I store a username "George"
When I login, I have to type exactly "George"."george" doesn't work.
Here is my code to compare.
if (userName.equalsIgnoreCase(resultString)) {
return true;
}
What might be the problem?
Please try following code,
if (userName.trim().equalsIgnoreCase(resultString.trim()))
{
return true;
}
Your code should work if the only difference is the case. I suspect you have leading or trailing spaces. Try the following:
if (userName.trim().equalsIgnoreCase(resultString.trim())) {
return true;
}
I was panic and didn't try the to print out the result.The problem was my query statement.
String whereClause = DatabaseHelper.USER_COL + " name =?";
The resultString is always empty unless input is the same as data.
To fix it I follow instruction in this post
sqlite LIKE problem in android
String whereClause = DatabaseHelper.USER_COL + " LIKE ?";
userName = userName+"%"
int Num;
String answer = et_q7.getText().toString();
String right_answer = "Air Pollution";
String right_answer2 = "Air";
if (answer.trim().equalsIgnoreCase(right_answer.trim()) || answer.trim().equalsIgnoreCase(right_answer2.trim())) {
Num = 1;
} else {
Num = 0;
}

unable to parse "" as integer[FC]

I have this code to control if a EditTextPreference is null or not:
case R.id.prochain_vidange:
settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String choix_huile = settings.getString("listPref_huile_moteur", "0");
km = settings.getString("km", "");
Log.d("TAG",km);
int x= Integer.valueOf(km);
if (km != "")
{
if (Integer.valueOf(choix_huile) == 0) {
............
The problem is in this line:
int x= Integer.valueOf(km);
What could be the problem ?
Thanks.
If you give Integer.valueOf(String s) a string that is not a valid number, it throws a NumberFormatException. Change the default value to 0:
km = settings.getString("km", "0");
Alternatively, you can catch the exception, and set x to 0:
km = settings.getString("km", "");
int x;
try {
x = Integer.valueOf(km);
} catch(NumberFormatException e) {
x = 0;
}
Integer.valueOf trys to make a new Integer with .parseInteger(String s), "" cant be parsed to a valid number so you get a NumberFormatException
You can catch it with a try catch block or you can simply dont try to make a Integer with the String "".
before:
int x= Integer.valueOf(km);
if (km != "") {
after:
if (km != "") {
int x= Integer.valueOf(km);
Integer.valueOf(km) can throw an exception if the the km string is not able to be parsed as an integer.
However, wrapping it in a try { } catch() block is not an approach I would recommend.
The whole purpose of having a default value on the getString() method in SharedPreferences is that there can be a default value to fall back on if the preference doesn't exist. So the better way to solve this is to modify your settings.getString(...) call to be like this:
km = settings.getString("km", "0");
Then your subsequent call to Integer.valueOf(km) will not have a blank to fail upon.
Is the input string coming from a blank text field where the user can enter any value? If so, it's at that point that you can validate the value that the user entered. By validating the input early on, you won't need to scatter the checking/validating mechanism to other areas of your code.

Categories

Resources