2015-11-13 50 views
1

我不知道爲什麼在運行時我收到blow posting錯誤,它說「嘗試在空引用上調用方法」試圖將對象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) 

回答

3

好吧,如果rfcSocket.isConnected()是假的,你不初始化this.mRFCOS,但您稍後再訪問它。

您應該在測試rfcSocket.isConnected()的if語句內移動第3個和第4個try-catch塊。