[英]What is going in in this IF-ELSE statement?
I'm really stuck here and it simply doesn't make any sense to me. 我真的被困在这里,对我来说根本没有任何意义。 Here's what's going on: I have an AsyncTask sending data to a server and retrieving a String response back.
这是怎么回事:我有一个AsyncTask将数据发送到服务器并检索String响应。 The String response can be two things: it can be a message telling the user that he/she is logged in if the credentials entered are correct or it can be a "FALSE" string which I use to display a notification toast to the user and take him/her back to the main activity to retry logging in.
字符串响应可以是两件事:它可以是一条消息,告知用户他/她是否输入了正确的凭据,也可以是“ FALSE”字符串,我用它来向用户显示通知消息,以及将他/她带回主要活动以重试登录。
Here is the code snippet: 这是代码片段:
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String cr = "Placeholder";
Credential cred = new Credential();
try { cr = cred.execute().get(); }
catch (InterruptedException e) { e.printStackTrace(); }
catch (ExecutionException e) { e.printStackTrace(); }
//tv.setText(cr);
if (cr == "FALSE") {
Log.d("Checking in false", cr);
Toast.makeText(Credentials.this, "Cannot log in: wrong username or password", Toast.LENGTH_LONG).show();
startActivity(new Intent(Credentials.this, MainActivity.class));
} else if (cr != "FALSE") {
Log.d("Checking in true", cr);
Intent intent = new Intent(Credentials.this, ProfileActivity.class);
intent.putExtra(INTENT_DATA, cr);
startActivity(intent);
}
}
});
By using the Log.d()
static method and looking at the LogCat, I'm sure that the returned value is indeed FALSE
if the credentials are wrong (again, it's not a boolean value, just String in all Caps). 通过使用
Log.d()
静态方法并查看LogCat,我可以确定如果凭据错误,则返回的值的确为FALSE
(再次,它不是布尔值,只是大写的String)。 The funny thing is that the code that gets executed is the "else if" part of the snippet I have posted but it actually logs that the returned string value is FALSE
! 有趣的是,执行的代码是我发布的代码段的“ else if”部分, 但实际上记录的是返回的字符串值为
FALSE
! Which means (at least to me) that it should have executed the first "if" condition (that is, if (cr == "FALSE") { }
). 这意味着(至少对我而言)意味着它应该已经执行了第一个“ if”条件(即
if (cr == "FALSE") { }
)。 But no, it keeps executing the "else if" part. 但是不,它会继续执行“ else if”部分。
Any ideas? 有任何想法吗?
Use equals for string comparisons. 将equals用于字符串比较。
IE: IE:
WRONG: 错误:
if (cr == "FALSE") {
CORRECT: 正确:
if (cr.equals("FALSE")) {
Use 采用
if (cr.contentEquals("false") {
//your code
} else {
//your code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.