简体   繁体   English

空字符串测试始终为true

[英]null string test is always true

I already saw a lot of similar posts, but none seems to be the same as this. 我已经看过很多类似的文章,但似乎没有一个与此相同。 I am testing if a string is null in my Java Android (2.2) app and whatever the string is, it is always true. 我正在测试我的Java Android(2.2)应用程序中的字符串是否为null,无论该字符串是什么,它始终为true。 Here is the code : 这是代码:

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 "";
    }
}

The if(name == null) is always true even if my string has a value. 即使我的字符串具有值,if(name == null)始终为true。 By the way, I also tried mBluetoothAdapter.getName() == null and it is always true too. 顺便说一句,我也尝试了mBluetoothAdapter.getName()== null,它也总是真实的。 I saw somewhere that you can do something like that: 我在某个地方看到可以执行以下操作:

if(name.equals("null")){

}

But if the string is null, wouldn't that create an exception because I should not be able to use a method if the object is null? 但是,如果字符串为null,那会不会创建异常,因为如果对象为null,则我将无法使用方法? Also, testing "null" is somewhat strange to me... 另外,测试“空”对我来说有点奇怪。

Try this simplified version : 试试这个简化版本:

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;
}

and don't forget to include android.permission.BLUETOOTH permission in your app's manifest. 并且不要忘记在应用的清单中包含android.permission.BLUETOOTH权限。

Also, note that sometimes your debugger may trick you by showing executing specific branches that are not in fact run (happened to me debugging in Eclipse before). 另外,请注意,有时您的调试器可能会通过显示实际上未运行的特定分支来欺骗您(这在我之前在Eclipse中调试)。 So, make sure that you ACTUALLY have Name is null output in logcat, otherwise your name may be not null . 因此,请确保您在logcat中Name is nullName is null输出,否则您的名称可能不为null

name = mBluetoothAdapter.getName();

由于name为null,因此您的Bluetooth适配器可能没有名称。

According to me, mBluetoothAdapter.getName() is always returning null, that is why the if condition is always returning true. 根据我的说法, mBluetoothAdapter.getName()始终返回null,这就是为什么if条件始终返回true的原因。 Your method of comparing if(name == null) is absolutely correct, no doubt in this. 毫无疑问,您比较if(name == null)是绝对正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM