【发布时间】:2014-08-07 16:38:50
【问题描述】:
我正在编写一个需要与蓝牙 2.1 设备交换数据的应用程序。 我已经做了好几次了,但这次发生了一些奇怪的事情。
Log.d("TAG", "connectToDevice");
if(macAddress != null)
deviceToConnect = mBluetoothAdapter.getRemoteDevice(macAddress);
Log.d("TAG", "macAddress != null");
if(deviceToConnect != null)
try {
btSocket = deviceToConnect.createRfcommSocketToServiceRecord(UUID.fromString(SharedIncludes.SPP_UUID));
} catch (IOException e) {
btSocket = null;
e.printStackTrace();
}
Log.d("TAG", "deviceToConnect != null");
if(btSocket != null){
try {
inputStream = btSocket.getInputStream();
Log.d("TAG", "inputStream OK");
} catch (IOException e) {
inputStream = null;
Log.d("TAG", "inputStream KO");
e.printStackTrace();
}
try {
outputStream = btSocket.getOutputStream();
Log.d("TAG", "outputStream OK");
} catch (IOException e) {
outputStream = null;
Log.d("TAG", "outputStream KO");
e.printStackTrace();
}
}
Log.d("TAG", "btSocket != null");
Log.d("TAG", "onConnectionEstablished");
在发现阶段之后,我获得了需要连接的蓝牙设备,然后获得了套接字、输入和输出流。
然后我有一个从输入流中读取的线程。
int byteRead;
while (listening) {
try {
if(inputStream!=null){
Log.d("TAG", "inputStream: " +inputStream);
byteRead = inputStream.read();
}else{
Log.d("TAG", "inputStream is null!");
continue;
} // Rest of the code here
执行inputStream.read() 行时出现此错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.io.InputStream.read(byte[], int, int)' on a null object reference
at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:427)
at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:60)
at com.me.testapplication.Connection_BT21.run(Connection_BT21.java:152)
问题 1:如果我检查 inputStream != null 为什么会出现 NullPointerException?
问题 2:如果我尝试调用 read(),为什么要 read(byte[], int, int)?
【问题讨论】:
-
问题 2:因为内部 read() 调用 read(byte[], int, int)。请注意调用上方的 android 框架内的 2 个步骤 问题 1:这不是在代码中引发异常,而是在框架内引发异常。所以不是你的输入流是空的,它是你的 inputStream 里面的一个 inputStream ,Android试图调用它。因此,null 表示框架错误或蓝牙套接字中的某些内容处于错误状态。
-
Connection_BT21.java 的第 152 行是什么?
-
@Husman:第 152 行是 inputStream.read()
-
@Gabe:好吧,这也是我的猜测,但你认为这可能与套接字有关还是与我正在使用的 android api 有关?
-
在哪里初始化 inputStream?它可能不为 null,但可能未处于准备好 read() 的状态,或者底层流可能尚未准备好。
标签: android bluetooth nullpointerexception inputstream