1

i am doing a project in android. i am a begineer in android also. in my android application i am using php as my webservice provider. in my php code for the authentication i am check the user vaidity and return string 1 or 0. In android application i am get the string. but when i check it in a if condition it fails. is it due to any charset compatablity issue.

in php code

.....
if($auth) {
 echo '1';
}
else {
 echo '0';
}

in android

//get the code and saved in to string loginStatus;
if(loginStatus == "1") {
 //not getting into this part if the loginStatus is 1;
}
else {
 //getting into this part
}
1
  • Try to debug. What is loginStatus value? Commented Nov 5, 2011 at 19:08

1 Answer 1

1

The == operator checks to see if two string references point to exactly the same string instance. So even if you have two strings that both have the value "1" the == operator can still return false.

To compare the strings character-by-character use String.equals:

if (loginStatus.equals("1")) {

To see the difference between == and equals see this simplified example:

String a = new String("1");
String b = new String("1");
System.out.println("a == b: " + (a == b));
System.out.println("a.equals(b): " + a.equals(b));

Result:

a == b: false
a.equals(b): true

See this code running online: ideone


Note: if loginStatus can be null you also need to check for that too, or else reverse the order of the strings so that the constant string is first:

if (loginStatus != null && loginStatus.equals("1")) {

Or:

if ("1".equals(loginStatus)) {
Sign up to request clarification or add additional context in comments.

3 Comments

i got working thanks buddy. but can you elaborate the issue with == operator. because i am new to the android and java development. can you share any post or article or if you don't mind can you post the reason here...
on doubt what mean by same string instance. like if i have a variable string test = '1'; and the string response = entity.tostring(); is the test == response returns false. they are all of same type.
@Jaison Justus: Strings are objects. If you create a new string, it's a new object. Analogy: If you meet two people called Peter it doesn't necessaily mean that it is the same exact same person. They could be two different people who happen to have the same name. Similarly two strings can different objects, but happen to contain the same characters. == will be false for these strings, but equals will be true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.