简体   繁体   中英

Check if string is equal to in Android/Java

I have an Android application. I'm trying to do a request to my webserver and retreive the response from the server. It seems working. Now I'm checking if the response is equal to success , The equal() function worked well for a while and seems stopped working.

How do I properly check if the output is equal to success ?

This is what I have tried:

if(LOGIN_AUTH.Login(usr, pwd, token).equals("success")) {
    // Server returned 'success'
    toDashboard();

}else {
    // Server returned something else then 'success'
    Alert("Error", LOGIN_AUTH.Login(usr, pwd, token));
    alert.dismiss();

    EditText password = (EditText) findViewById(R.id.login_ip_password);

    assert password != null;
    password.setText("");
}

I also added .trim() as I found this question: Android string .equals method not working . I tried that solution, but it's not working for me.

In the Login() function also trimmed the output like this:

return postResponse.trim().toString();

For some reason the application skipped the check and triggers the Alert() function. This alert showed me that the server returned success and there were no whitespaces, special characters or line-breaks found in the output.

在此输入图像描述

Maybe .contentEquals() is what you are looking for.
equals(Object o) return true/false on any type of data, depends if the content is equal or not !

contentEquals(CharacterSequence cs) returns true if and only if this String represents the same sequence of characters as the specified StringBuffer. You can read more about the difference at this link .
Also,the function is well described here .

Try to log what

LOGIN_AUTH.Login(usr, pwd, token)

is returning. It might not return what you think it returns.

Then, the good practice is to either flip your equals condition to:

"success".equals(LOGIN_AUTH.Login(usr, pwd, token))

(to avoid getting NullPointerException when the response is null) or user Android platform's class called TextUtils:

TextUtils.equals("success", LOGIN_AUTH.Login(usr, pwd, token))

If it's still not working, log the server response (as suggested above) and post the log somewhere. I will update my answer accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM