如何在BluetoothSocket上修复设备的null和nullpointer

时间:2019-01-14 22:46:53

标签: java android chat android-bluetooth

我从Java开始,正在尝试创建一个android蓝牙聊天应用程序,但是现在Im面临此NullPointerException,似乎空设备是问题所在,但我仍然不知道如何解决此问题。直到发现并建立蓝牙为止一切都很好,然后我开始寻找聊天教程和示例并制作了这个。

java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.BluetoothSocket android.bluetooth.BluetoothDevice.createRfcommSocketToServiceRecord(java.util.UUID)' on a null object reference
        at com.example.gabriel.eden.MainActivity$ConnectThread.run
@Override
protected void onStart(){
    super.onStart();
    getPairedDevices();
    buttonSearch.setOnClickListener(clicked);
    newDevices.setOnItemClickListener(listItemClicked);
}

private void getPairedDevices(){
    Set<BluetoothDevice> pairedDevice = mBTAdapter.getBondedDevices();
    if(pairedDevice.size() > 0 ){
        for (BluetoothDevice device : pairedDevice){
            arrayListPaired.add(device.getName() + "\n" + device.getAddress());
            arrayListPairedBluetoothDevices.add(device);

            ConnectThread connect = new ConnectThread(mBTDevice,MY_UUID);
            connect.start();

        }
    }
}
  private class ConnectThread{

    public ConnectThread(BluetoothDevice device, UUID uuid){
        Log.d(TAG,"ConnectedThread: started");
        mBTDevice = device;
        deviceUUID = uuid;
    }

    public void run(){
        Log.i(TAG, "RUN mConnectThread ");
        BluetoothSocket tmp = null;

        try {
            Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket using UUID: " + MY_UUID);
            tmp = mBTDevice.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket " + e.getMessage());
        }

        mSocket = tmp;

        //Connection to the bluetoothsocket
        try {
            //only return a successful connection or exception
            mSocket.connect();
        } catch (IOException e) {
            try {
                mSocket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }

}

0 个答案:

没有答案