Question

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. 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. By the way, I also tried mBluetoothAdapter.getName() == null and it is always true too. 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? Also, testing "null" is somewhat strange to me...

Was it helpful?

Solution

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.

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). So, make sure that you ACTUALLY have Name is null output in logcat, otherwise your name may be not null.

OTHER TIPS

name = mBluetoothAdapter.getName();

Since name is null, your Bluetooth adapter probably doesn't have a name.

According to me, mBluetoothAdapter.getName() is always returning null, that is why the if condition is always returning true. Your method of comparing if(name == null) is absolutely correct, no doubt in this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top