gpt4 book ai didi

java - 蓝牙 mConnectedThread 的 NullPointerException

转载 作者:行者123 更新时间:2023-11-30 03:02:42 26 4
gpt4 key购买 nike

为什么mConnectedThread会出现NullPointerException错误?手机与远程设备之间的蓝牙连接已建立。

这是代码的主要部分,错误是:

public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
r = mConnectedThread;
System.out.println(out);
}
// Perform the write unsynchronized
r.write(out);
System.out.println(out);
}

ConnectedThread.java代码:

private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;

public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;

try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}

mmInStream = tmpIn;
mmOutStream = tmpOut;
}

public void run() {
byte[] buffer = new byte[1024];
int bytes;

// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);

// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(MenuActivity.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}

/**
* Write to the connected OutStream.
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
System.out.println("Sent");
// Share the sent message back to the UI Activity
//mHandler.obtainMessage(MenuActivity.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}

最佳答案

香农有问题。

您只声明了 mConnectedThread

private ConnectedThread mConnectedThread;

它尚未初始化,默认情况下它的值为 null,您已将其分配给

 r = mConnectedThread; 

因此 r 也为空。这样做,

r.write(out);

生成了 NullPinterException。

确保您已经初始化了 mConnectedThread 变量。

关于java - 蓝牙 mConnectedThread 的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22320359/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com