对于android中的登录页面,我使用php webservice连接到服务器数据库。我将来自php服务的响应存储在一个字符串中。响应应该是成功还是失败。但有时它既不会成功也不会失败。所以那时它显示空指针异常。我尝试如下,但它在行
显示空指针异常if(!response.equals(null)&& response.equals(“SUCCESS”))
当响应为空时。我该如何解决这个问题。请帮助我。
if (!response.equals(null) && response.equals("SUCCESS")) {
Intent howis = new Intent(Login.this, Homepage.class);
startActivity(in);
}
else if (response.equals("FAILED")) {
new AlertDialog.Builder(Login1.this)
.setMessage(
"Sorry!! Incorrect Username or Password")
.setCancelable(false).setPositiveButton("OK", null)
.show();
password.setText("");
username.requestFocus();
} else if (response.equals(null)) {
new AlertDialog.Builder(Login1.this)
.setMessage("Invalid email or password")
.setCancelable(false).setPositiveButton("OK", null)
.show();
password.setText("");
username.requestFocus();
} else {
new AlertDialog.Builder(Login1.this)
.setMessage("Please Try Again..")
.setCancelable(false).setPositiveButton("OK", null)
.show();
password.setText("");
username.requestFocus();
}
答案 0 :(得分:2)
如果您要检查空(其中没有任何内容)字符串,则条件应为:
if (response == null) {
} else if (response != null) {
}
如果您要检查 null 的String
值(String中的值为null),则条件应为:
if (response.equals("null")) {
} else {
}
答案 1 :(得分:1)
equals()
时,您无法使用null
等字符串的方法。您应首先检查null
(response == null
)。
我建议做
if (response == null) {
//null
} else if (response.equals("SUCCESS")) {
//success
} else if (response.equals("FAILED")) {
//failed
} else {
//neither of those
}
或
if (!response == null && response.equals("SUCCESS")) {
//success
} else if (!response == null && response.equals("FAILED")) {
//failed
} else if (response == null) {
//null
} else {
//neither of those
}
第一种方式更短,更简洁,第二种方式是代码排序,更好的理解代码。
答案 2 :(得分:0)
您也可以使用
if(TextUtils.isEmpty(response))
{
// response is either null or empty
}
来自文档:
public static boolean isEmpty (CharSequence str)
Returns true if the string is null or 0-length.
答案 3 :(得分:0)
你可以简单地使用..
if (!response.equals("") && response.equals("SUCCESS"))
{
...
}
答案 4 :(得分:0)
另一种可行的解决方法(适用于我)是通过在布局xml中设置默认值来避免空指针异常:
机器人:文本= “SomeText” 则会
如果你卡住了: - )