title: inputStream.read() causes NullPointerException (after having checked inputStream!=null)
body: <p>I am writing an application that needs to exchange data with a Bluetooth 2.1 device.
  I have done it several times but this time something weird is happening.</p>
  
  <pre><code>    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");
  </code></pre>
  
  <p>After the discovering phase I get the BluetoothDevice I need to connect to and then I obtain the socket, input &amp; output streams.</p>
  
  <p>I then have a thread that reads from the input stream. </p>
  
  <pre><code>   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
  </code></pre>
  
  <p>I get this error while executing the <code>inputStream.read()</code> line:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>Problem 1: why NullPointerException if I am checking that inputStream != null?</p>
  
  <p>Problem 2: why read(byte[], int, int) if I am trying to call read()?</p>