简体   繁体   中英

NullPointerException when passing values from an activity to another

Why is there a NullPointerException error when I try to pass the data from an activity and write it to OutputStream to send to a remote Bluetooth device?

In activity A:

BluetoothConnection mSendMessage = new BluetoothConnection();
mSendMessage.send();

In BluetoothConnection:

public ConnectedThread mConnectedThread;

public synchronized void ConnectedThread(BluetoothSocket socket){
    ConnectedThread mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();
}

public void send() throws IOException{                  
    byte[] byteString = (1 + " ").getBytes();
    mConnectedThread.write(byteString);
}

In ConnectedThread:

public void run(){
    byte[] buffer = new byte[1024]; 
    int bytes;      

    while (true) {
      try {
          bytes = mmInStream.read(buffer);
      } catch (IOException e) {
    break;
    }
  }
}

public void write (byte[] buffer){
try{
     mmOutStream.write(buffer);          
}catch(IOException e){
}
}

The NullPointerException occurred at the line "mSendMessage.send()" in activity A. The bluetooth connection between the phone and device is established already. mmOutStream and mmInStream are defined as

mmInStream = socket.getInputStream();
mmOutStream = socket.getOutputStream();

Additional question: If nothing is sent from the remote Bluetooth Device to the phone, does the while(true) loop blocks the whole code such that write() method is never called? Could it be possible?

As I can see you're doing a tiny mistake, Null Pointer Exception only comes when a variable does not initialize before use. You need to change your code a little as following :

public synchronized void ConnectedThread(BluetoothSocket socket){
    mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();
}

The problem was, you have made local instance of ConnectedThread class which does not contain any data to send. Just replace "ConnectedThread()" function with the above. Hope you can understand now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM