当我尝试从活动传递数据并将其写入OutputStream以发送到远程蓝牙设备时,为什么会出现NullPointerException
错误?
在活动A:
BluetoothConnection mSendMessage = new BluetoothConnection();
mSendMessage.send();
在BluetoothConnection中:
public ConnectedThread mConnectedThread;
public synchronized void ConnectedThread(BluetoothSocket socket){
ConnectedThread mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
}
public void send() throws IOException{
byte[] byteString = (1 + " ").getBytes();
mConnectedThread.write(byteString);
}
在ConnectedThread中:
public void run(){
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
} catch (IOException e) {
break;
}
}
}
public void write (byte[] buffer){
try{
mmOutStream.write(buffer);
}catch(IOException e){
}
}
NullPointerException
发生在活动A中的“mSendMessage.send()”行。手机和设备之间的蓝牙连接已经建立。 mmOutStream和mmInStream定义为
mmInStream = socket.getInputStream();
mmOutStream = socket.getOutputStream();
附加问题:如果没有从远程蓝牙设备向手机发送任何内容,while(true)循环是否会阻止整个代码,从而永远不会调用write()方法?有可能吗?
答案 0 :(得分:4)
正如我可以看到你犯了一个小错误,Null Pointer Exception仅在变量未在使用前初始化时出现。您需要稍微更改一下代码:
public synchronized void ConnectedThread(BluetoothSocket socket){
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
}
问题是,你已经创建了ConnectedThread类的本地实例,它不包含任何要发送的数据。只需用上面的代码替换“ConnectedThread()”函数即可。希望你现在能理解。