通常我会在每个 Activity (Android)中进行比较,但我遇到了问题并且找不到解决方案。我尽了一切努力,但结果还是一样。
在 if 语句中 null
值似乎不为 null。
我做错了什么?
这是代码:
System.out.println(item.getSub()); // output is null
if (item.getSub()!=null) {
r.putExtra("engsub", item.getSub()); // Normally it shouldn't, but it goes in here
startActivityForResult(r, position);
}
else {
//Do something
}
我尝试了这个:
String def = item.getSub()+"";
System.out.println(def); // output is not null
if (!def.equals("")) {
r.putExtra("engsub", item.getSub()); // Normally it shouldn't, but it goes in here
startActivityForResult(r, position);
}
else {
//Do something
}
已添加:
JSONArray jsonResponse = new JSONArray(result);
asd = new String[5][jsonResponse.length()];
rowItems = new ArrayList<RowItem2>();
for (int i = 0; i < jsonResponse.length(); i++) {
JSONObject js = jsonResponse.getJSONObject(i);
// ....codes
asd[4][i] = js.getString("engsub");;
item = new RowItem2(asd[0][i], asd[1][i], asd[2[i],
asd[3][i],asd[4][i]);
rowItems.add(item);
}
RowItem2 类
private String engsub;
public RowItem2(String title, String desc,String desc2,String desc3,String engsub) {
this.engsub = engsub;
//......
}
//.......
public String getSub() {
return engsub;
}
public void setSub(String engsub) {
this.engsub = engsub;
}
最佳答案
我认为 JSON 字符串 result
中包含单词“NULL”。
查看有关 JSONObject on Android Developer site 的文档.
这是解决您的问题的行:
<小时/>When the requested type is a String, other non-null values will be coerced using valueOf(Object). Although null cannot be coerced, the sentinel value NULL is coerced to the string "null".
以下是尝试追踪此类问题时的一些想法:
<小时/>确认你的假设
你听起来很困惑,所以放心吧。 Java/Android没有任何问题。通过每次都能正常工作的更改来确认这一点。
此更改挑战了您的假设:您假设 item.getSub()
返回 null
。
String nullString = null;
System.out.println(nullString);
if (nullString != null) {
r.putExtra("engsub", item.getSub()); // Normally it shouldn't, but it goes in here
startActivityForResult(r, position);
}
else {
//Do something
}
这不会通过 if
测试,除非您的 IDE 有问题。
确认您的 IDE 正在运行
您可能仍然认为您得到的是null
。在某些情况下,它可能看起来像这样。
有时 Eclipse 不会将正确的代码放入您的模拟器/设备上。构建可能存在问题。
所以做一个 Clean 项目。然后再次构建并测试。
这将确认您正在运行正确的代码。
<小时/>确认您所看到的内容
有时,当输出看起来像“”字符串时,它可以是“”或“”。
尝试记录用 [ 和 ] 包围的输出。
System.out.println("[" + item.getSub() + "]");
<小时/>
深入研究代码
这就是为什么我要求查看 item.getSub()
代码以及您所显示的额外内容。
如果上述测试没有帮助,请查看如何设置/返回该值。
调查JSONObject.getString()
javadoc ,它表明它不能返回 null
值:
在您的情况下,注销 JSON 字符串,并注销 RowItem2
构造函数中的值。
这应该向您显示我在这个答案顶部提到的“NULL”。
关于java - 比较中的空值似乎不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23782750/