为什么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也为null。这样做,

r.write(out);


生成了NullPinterException。

确保已初始化mConnectedThread变量。

10-08 01:10