Reputation: 589
Why is there a NullPointerException error for mConnectedThread? The Bluetooth connection between the phone and remote device is established.
Here is the main part of the code where the error is:
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 code:
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);
}
}
Upvotes: 1
Views: 806
Reputation: 6792
Theres the problem shannon.
You have only declared mConnectedThread by doing,
private ConnectedThread mConnectedThread;
Its yet not initialized and by default its value is null which you have assigned to
r = mConnectedThread;
hence r is also null. Thus doing,
r.write(out);
generated the NullPinterException.
Make sure you have initiazed the mConnectedThread variable.
Upvotes: 1