指向int java.io.InputStream.read(byte[],int,int)的NullPointerEx



我一直在学习BluetoothChat应用程序教程,该教程类似于谷歌提供的示例。链接到这里的参考GoogleSource。当我还没有实现处理输入和输出流的类时,我可以成功连接到其他手机的蓝牙。但是当我实现类(ConnectedThread(时,它在"上的run((方法处用空指针异常使应用程序崩溃字节=inputSream.read(缓冲区(";在那个班级里。你知道如何解决问题吗?困扰我好几天了。我们将不胜感激。谢谢

ConnectedThread类

private class ConnectedThread extends Thread {
private final BluetoothSocket bluetoothsocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public ConnectedThread(BluetoothSocket socket) {
bluetoothsocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = bluetoothsocket.getInputStream();
tmpOut = bluetoothsocket.getOutputStream();
} catch (IOException e) {
Log.e("ConnectedThrd->Cons", "Socket not created.");
}
inputStream = tmpIn;
outputStream = 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
//App crashes here(?)
bytes = inputStream.read(buffer);
// Send the obtained bytes to the UI Activity
handler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e("ConnectedThrd->Run", "Connection Lost.", e);
e.printStackTrace();
connectionLost();
break;
}
}
}
public void write(byte[] buffer) {
try {
outputStream.write(buffer);
handler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e("ConnectedThread->Write", "Empty write stream.");
}
}
public void cancel() {
try {
bluetoothsocket.close();
} catch (IOException e) {
Log.e("ConnectedThread->Cancel", "Failed to close socket.");
}
}
}

问题是,当我试图将数据发送到导致此错误的其他设备时,BluetoothSocket为null。添加一个检查连接是否已建立的条件帮助我处理了这个错误。

最新更新