我已经看过很多类似的帖子,但似乎没有一个与此相同。我正在测试我的 Java Android (2.2) 应用程序中的字符串是否为 null,并且无论字符串是什么,它始终为 true。这是代码:
public static String getLocalBluetoothName(){
String name;
if(mBluetoothAdapter == null){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
try{
name = mBluetoothAdapter.getName();
if(name == null){
System.out.println("Name is null!");
name = mBluetoothAdapter.getAddress();
}
return name;
}
catch (Exception e){
return "";
}
}
即使我的字符串有值,if(name == null) 也始终为 true。顺便说一句,我也尝试过 mBluetoothAdapter.getName() == null ,它也总是正确的。我在某个地方看到你可以做类似的事情:
if(name.equals("null")){
}
但是如果字符串为空,那不会产生异常吗?因为如果对象为空,我不应该使用方法?另外,测试“null”对我来说有点奇怪......
最佳答案
尝试这个简化版本:
public static String getLocalBluetoothName(){
String name = null;
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null) {
//System.out.println("Can't get adapter");
Log.d(TAG, "Can't get adapter");
return name;
}
if ((name = adapter.getName()) == null) {
//System.out.println("Name is null!");
Log.d(TAG, "Name is null!");
name = adapter.getAddress();
}
return name;
}
并且不要忘记在应用的 list 中包含 android.permission.BLUETOOTH
权限。
另外,请注意,有时您的调试器可能会通过显示正在执行的特定分支来欺骗您,而这些分支实际上并未运行(我之前在 Eclipse 中调试时就遇到过这种情况)。因此,请确保 logcat 中确实有 Name is null
输出,否则您的名称可能不是 null
。
关于java - 空字符串测试始终为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23296187/