我已经看过很多类似的帖子,但似乎没有一个与此相同。我正在测试我的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,那会不会创建异常,因为如果对象为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;
}


并且不要忘记在应用的清单中包含android.permission.BLUETOOTH权限。

另外,请注意,有时您的调试器可能会通过显示实际上未运行的特定分支来欺骗您(这在我之前在Eclipse中调试)。因此,请确保您在logcat中确实有Name is null输出,否则您的名字可能不是null

关于java - 空字符串测试始终为true,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23296187/

10-12 00:27
查看更多