Wesley Peeters Wesley Peeters - 1 month ago 10
Android Question

String.equals() always returns false?

I am trying to make a sign in page for an android app. My team leader has decided to make this with a webservice.

Whenever a uses logs in, a request is sent, with 3 possible responses:

0: Wrong Password
20: Wrong username
otherwise: a UUID


I am trying to validate the results given back by the webservice like this:

String resultString = result.toString();
if (resultString.equals("20")) {
Toast.makeText(getBaseContext(), "Het ingevulde emailadres klopt niet!", Toast.LENGTH_LONG).show();
return;
} else if (resultString.equals("0")) {
Toast.makeText(getBaseContext(), "Het ingevulde wachtwoord klopt niet!", Toast.LENGTH_LONG).show();
return;
} else {
Toast.makeText(getBaseContext(), "Debug, klopt", Toast.LENGTH_LONG).show();
return;
}


Seems like basic code to me. However, this code always shows the bottom statement, so it lets the first 2 pass as false.

For debugging purposes, am also returning the
resultString
to my console. (removed that line in the sample). There I can very obviously see that the result given back is in fact
20
.

How can it be that such simple code does not do what I want it to do?

Thanks.

Answer

Response is not exactly the string you are comparing which are "0" and "20". but the response is

0: Wrong Password
20: Wrong username
otherwise: a UUID

if you want to compare the string then it should be

Options : 1

String resultString = result.toString();
if (resultString.equals("20: Wrong username")) {
    // code
} else if (resultString.equals("0: Wrong Password")) {
    // code
} else {
    // code
}

Option : 2

Instead of eqauls you should use contains

String resultString = result.toString();
if (resultString.contains("20")) {
    // code
} else if (resultString.contains("0")) {
    // code
} else {
    // code
}