I am brand new to Java and Android so I am sure this will be an easy question/answer. I know that to find out if a string is equal to another string you use the equal function. In my situation, I am scanning a QR Code where the result of the scan is Similar to "EMPLOYEE~~John Smith~~DIVISION~~Maintenance". I need to know how to do the following:
String contents = intent.getStringExtra("SCAN_RESULT");
// I know that "contents" contains the string " EMPLOYEE~~John Smith~~DIVISION~~Maintenance"
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
String val1 = myJunk[0];
// Now val1 Should be equal to "EMPLOYEE"
if (myJunk[0].equals(val1)){
// Do Something
}
In the example Java Code, myJunk[0] never equals val1. What am I doing wrong?
i've tried this and it works , so try to display the contents variable , probably the problem is in the extras , try to display it in logCat :
String contents = "EMPLOYEE~~John Smith~~DIVISION~~Maintenance";
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
String val1 = myJunk[0];
Toast.makeText(this, "val1 = "+val1, Toast.LENGTH_LONG).show();
Toast.makeText(this, "val2 = "+myJunk[1], Toast.LENGTH_LONG).show();
// Now val1 Should be equal to "EMPLOYEE"
if (myJunk[0].equals(val1)){
Toast.makeText(this, "equals", Toast.LENGTH_LONG).show();
}
Your string is:
EMPLOYEE~~John Smith~~DIVISION~~Maintenance
So after spliting, myJunk[0] will contain EMPLOYEE (notice the space in front of the word EMPLOYEE).
So before comparing , you will need to trim your value
The method i usually use, is to print out my variables when in doubt. So if you are unsure of where the problem is, you could try something like this.
(It requires you to be able to see the output, in logcat for example)
String contents = intent.getStringExtra("SCAN_RESULT");
// I know that "contents" contains the string " EMPLOYEE~~John Smith~~DIVISION~~Maintenance"
System.out.println("contents is "+contents );
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
System.out.println("Array size is "+myJunk.length);
String val1 = myJunk[0];
// Now val1 Should be equal to "EMPLOYEE"
for(int i=0; i < myJunk.length; i++) {
System.out.println("String "+i+ "in array is: "+myJunk[i]);
}
//Here i run through the array and print every element.
if (myJunk[0].equals(val1)){
// Do Something
}
It is a bit overkill, but this is mostly to show one way of getting all the information you need to find the problem :)
Related
I am writing an app with Android Studio and I want to split a text into different values.
I have following text in result
*"Name: Peter;Age: 25; City: Chicago"*
I want to get:
*Name = Peter;
Age = 25;
City = Chicago;*
I used the search function and found these solutions: Android Split string but for my problem it seems to be too complicated.
The easiest way is to use split() method.
String s1="Name: Peter;Age: 25; City: Chicago";
String[] words=s1.split(";");
//using java foreach loop to print elements of string array
for(String w:words)
{
Log.i("Words: ", w);
}
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).
I've seen many people do similar to this in order to get the last word of a String:
String test = "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);
I would like to do similar but get the last few words after the last int, it can't be hard coded as the number could be anything and the amount of words after the last int could also be unlimited. I'm wondering whether there is a simple way to do this as I want to avoid using Patterns and Matchers again due to using them earlier on in this method to receive a similar effect.
Thanks in advance.
I would like to get the last few words after the last int.... as the number could be anything and the amount of words after the last int could also be unlimited.
Here's a possible suggestion. Using Array#split
String str = "This is 1 and 2 and 3 some more words .... foo bar baz";
String[] parts = str.split("\\d+(?!.*\\d)\\s+");
And now parts[1] holds all words after the last number in the string.
some more words .... foo bar baz
What about this one:
String test = "a string with a large number 1312398741 and some words";
String[] parts = test.split();
for (int i = 1; i < parts.length; i++)
{
try
{
Integer.parseInt(parts[i])
}
catch (Exception e)
{
// this part is not a number, so lets go on...
continue;
}
// when parsing succeeds, the number was reached and continue has
// not been called. Everything behind 'i' is what you are looking for
// DO YOUR STUFF with parts[i+1] to parts[parts.length] here
}
I have a string like this:
_id:2 thread_id:189 address:0292 m_size:null person:0 date:1372494272447 date_sent:0 protocol:0 read:1 status:-1 type:1 reply_path_present:0 subject:null body:Ok. Reply message. service_center:051108 locked:0 sim_id:0 error_code:0 seen:1 _id:1 thread_id:189 address:292 m_size:null person:0 date:1372493695831 date_sent:0 protocol:null read:1 status:-1 type:2 reply_path_present:null subject:null body:Test message service_center:null locked:0 sim_id:0 error_code:0 seen:0
I want to retrieve only parts of this string, for example the address:0292 and the body:xyz from the entire string. I want all instances of these two from a very large String (above is just a sample). Let's assume its more than 20000 characters.
How can I achieve this?
Looks like every address is followed by m_size, so use the string.split() function, to split over the keyword address then select the string.substring() (from each string in the resulting array) until reaching the keyword m_size. And repeat the entire thing for the keywords body and service_center. I can't think of any other way.
You are right, it doesn't seem pretty. But it works :)
String[] splitString = string.split(" ");
for (int i = 0; i < splitString.length; i++) {
if (splitString[i].startsWith("body") || splitString[i].startsWith("address"))
Log.i(TAG, "Found: " + splitString[i]);
// Do whatever you need to do
}
i have this code in my app. which accepts the value of the edittext
if (ans.equalsIgnoreCase("bag")) {
btnEnter.setEnabled(false);
int a=Integer.parseInt(textView2.getText().toString());
int b=a+10;
String s1 = String.valueOf(b);
textView2.setText(s1);
Toast.makeText(getApplicationContext(), "Correct",Toast.LENGTH_SHORT).show();
my problem is if the user puts a single space in the edittext then proceeds with the "bag" it still prompts wrong like this for example
" " = space
" " bag ----- wrong
bag ----- correct
how can i set that with space it can accept
String ans2 = ans.trim();
if (ans2.equalsIgnoreCase("bag")) {
btnEnter.setEnabled(false);
int a=Integer.parseInt(textView2.getText().toString());
int b=a+10;
String s1 = String.valueOf(b);
textView2.setText(s1);
Toast.makeText(getApplicationContext(), "Correct",Toast.LENGTH_SHORT).show();
trim() function
Returns a copy of the string, with leading and trailing whitespace
omitted.
Since #ρяσѕρєя K deleted his answer before I got back to delete mine I will add his simplified edit. Change
if (ans2.equalsIgnoreCase("bag")) {
to
if (ans.trim().equalsIgnoreCase("bag")) {
then no need for
String ans2 = ans.trim();
But using a second variable may be better for readibility or functionality in certain situations
Edit
To take care of in between spaces you might try
if (!ans.contains("") && ans.trim().equalsIgnoreCase("bag")) {
Not sure why that doesn't work but you can use the replace function for Strings
String ans2 = ans.replace(" ", "");
if (ans2.trim().equalsIgnoreCase("bag")) {