初始化后,对象为null

时间:2015-11-13 09:03:23

标签: java android

我不知道为什么在运行时我会收到发布错误,它说"尝试在空引用上调用方法" despit对象mRFCOS被赋值为一个值。

代码中出现了什么问题

运行()中的

private class RxRun implements Runnable {

    private BluetoothSocket mRFCSocket = null;
    private OutputStream mRFCOS = null;
    private InputStream mRFCIS = null;

    public RxRun() {
        mSPPCtrl = new SPPCtrl(getApplicationContext());
    }

    @Override
    public void run() {

        //initiating connection
        BluetoothSocket rfcSocket = mSPPCtrl.rfcConnect();

        if (rfcSocket.isConnected()) {
            Message msg = mHandler.obtainMessage(1);
            Bundle b = new Bundle();
            b.putString("CONNECTED", "RFC-SOCKET CONNECTED");
            msg.setData(b);
            mHandler.sendMessage(msg);
            //assigning stream variables
            try {
                this.mRFCOS = rfcSocket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                this.mRFCIS = rfcSocket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            Message msg = mHandler.obtainMessage(0);
            Bundle b = new Bundle();
            b.putString("DISCONNECTED", "RFC-SOCKET NOT CONNECTED");
            msg.setData(b);
            mHandler.sendMessage(msg);
        }

        //send a command to RFC-socket
        try {
            this.mRFCOS.write(DIRON.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        //read received response from RFC-socket
        int readBytes;
        try {
            while (this.mRFCSocket.isConnected() && (readBytes = this.mRFCIS.read(new byte[5120])) != -1) {
                Log.d(TAG, CSubTag.bullet("RxRun", "readBytes:" + readBytes));
                //mtvRx.setText("" + readBytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

logcat的

11-13 09:55:49.557 11833-12423/com.example.com.rfcomm_test_00 E/AndroidRuntime: FATAL EXCEPTION: Thread-20426
11-13 09:55:49.557 11833-12423/com.example.com.rfcomm_test_00 E/AndroidRuntime: Process: com.example.com.rfcomm_test_00, PID: 11833
11-13 09:55:49.557 11833-12423/com.example.com.rfcomm_test_00 E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[])' on a null object reference
11-13 09:55:49.557 11833-12423/com.example.com.rfcomm_test_00 E/AndroidRuntime:     at com.example.com.rfcomm_test_00.MainActivity$RxRun.run(MainActivity.java:90)
11-13 09:55:49.557 11833-12423/com.example.com.rfcomm_test_00 E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:818)

1 个答案:

答案 0 :(得分:3)

好吧,如果rfcSocket.isConnected()为false,则不会初始化this.mRFCOS,但您稍后会访问它。

你应该在测试rfcSocket.isConnected()的if语句中移动第3和第4个try-catch块。