Android String Not Equal
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 follo开发者_运维技巧wing:
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 :)
精彩评论