Java 为什么BluetoothSocket的输入/输出流被计算为NOTNULL,然后抛出null指针异常?

Java 为什么BluetoothSocket的输入/输出流被计算为NOTNULL,然后抛出null指针异常?,java,android,sockets,bluetooth,nullpointerexception,Java,Android,Sockets,Bluetooth,Nullpointerexception,我有一个从蓝牙套接字创建的inputstream和outputstream,在检查套接字是否为空(这都在OnCreate函数中)后,我尝试向其写入内容: 无论蓝牙设备是否已连接或在范围内,输出流都将被评估为非空,并尝试写入。此写入尝试触发空指针异常 为什么会发生这种情况?为什么outputStream在一行上求值为NOT null,然后在下一行上立即抛出null指针异常?我用几个不同的配对蓝牙设备尝试了这个方法,得到了相同的结果 java.lang.NullPointerException:

我有一个从蓝牙套接字创建的inputstream和outputstream,在检查套接字是否为空(这都在OnCreate函数中)后,我尝试向其写入内容:

无论蓝牙设备是否已连接或在范围内,输出流都将被评估为非空,并尝试写入。此写入尝试触发空指针异常

为什么会发生这种情况?为什么outputStream在一行上求值为NOT null,然后在下一行上立即抛出null指针异常?我用几个不同的配对蓝牙设备尝试了这个方法,得到了相同的结果

 java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[], int, int)' on a null object reference
outputStream
从不为null,因此您的null检查将始终返回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.
理想情况下,根据文档,它应该抛出
IOException

mSocket.write(b,0,1)
使用
mSocketOS
,它是
null
并导致异常。 使用API>=21,您将获得消息“write在null OutputStream上被调用”的
IOException

您可以使用
btsocket.connect()
来初始化所需的
mSocketOS

在写入套接字之前,您应该调用
isConnected()
,只有在与远程设备有活动连接时,它才会返回true

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

OutputStream
为空。请看例外情况。检查
isConnected()
通常是徒劳的。如果连接断开,它不会神奇地变成false。是的,但是outputStream null不是OP使用的。API总是返回非null outputStream。@EJP“isConnected()通常是无效的”,但在这种情况下它返回的不是最新状态。public boolean isConnected(){return mSocketState==SocketState.CONNECTED;}
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.
public void write(int oneByte) throws IOException {
    byte b[] = new byte[1];
    b[0] = (byte)oneByte;
    mSocket.write(b, 0, 1);
}
 if(btsocket.isConnected()) {
     outputStream.write(1);
 }