简体   繁体   中英

Why do input/outputstream from BluetoothSocket get evaluated as NOT null, then throw null pointer exception?

I have an inputstream and outputstream created from a bluetooth socket that I try to write something to after checking if the socket is null (this is all within the OnCreate function):

BluetoothDevice btDevice = ...//get bluetooth device from user's selection of paired devices

UUID MY_UUID = btDevice.getUuid();

BluetoothDevice remotedevice = btAdapter.getRemoteDevice(btDevice.getAddress());

BluetoothSocket btsocket = remotedevice.createRfcommSocketToServiceRecord(MY_UUID);

InputStream inputStream = btsocket.getInputStream();
OutputStream outputStream = btsocket.getOutputStream();

if (outputStream != null){
         outputStream.write(1);
}

Whether or not the bluetooth device is connected or in range, the output stream will be evaluated as NOT null and the attempt will be made to write to it. This write attempt is what triggers the null pointer exception.

Why does this happen? Why is the outputStream evaluated NOT null on one line, and then throws a null pointer exception immediately on the next line? I've tried this with a few different paired bluetooth devices and get the same result.

 java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[], int, int)' on a null object reference
OutputStream outputStream = btsocket.getOutputStream();

outputStream is never null, so your null check will always return true.

OutputStream getOutputStream ()
Get the output stream associated with this socket.

The output stream will be returned even if the socket is not yet connected, but operations on that stream will throw IOException until the associated socket is connected.

Ideally as per documentation it should throw IOException (and it does so for API LEVEL >= 21)

public void write(int oneByte) throws IOException {
    byte b[] = new byte[1];
    b[0] = (byte)oneByte;
    mSocket.write(b, 0, 1);
}

mSocket.write(b, 0, 1) uses mSocketOS which is null and causing the exception. With API >= 21 you will get IOException with message "write is called on null OutputStream"

You can use btsocket.connect() to initiate the outgoing connection which will initialize required mSocketOS .

Before writing to socket you should call isConnected() which will return true only if there is an active connection with remote device.

 if(btsocket.isConnected()) {
     outputStream.write(1);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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