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