0

Why am I getting a NullPointerException when trying to send a byte[] over bluetooth? It happens when mConnectedThread.write(mOutput); is called in the main class near the bottom, right before the inner ConnectThread class. I've been writing logs to the console and they all say the byte isn't null, but it still refuses to be sent. Here's my main class:

public class bluetoothMusicListener extends AppCompatActivity {

BluetoothAdapter mBluetoothAdapter;
Context          mContext;
ConnectedThread  mConnectedThread;
ConnectThread    mConnectThread;
Handler          mHandler;
View             mConnectToDevices;
View             mSendText;
BluetoothDevice  mDevice;
ParcelUuid       list[];

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bluetooth_listener);

    mConnectToDevices = findViewById(R.id.connectToDevices);
    mSendText = findViewById(R.id.sendText);

    mContext = getApplicationContext();

    mBluetoothAdapter = mBluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        Toast.makeText(mContext, "No bluetooth adapter found", Toast.LENGTH_SHORT).show();
    }

    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, 1);
    }

    mConnectToDevices.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            //BluetoothDevice mDevice[] = (BluetoothDevice)pairedDevices.toArray();

            if (pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    mDevice = device;
                    list = device.getUuids();
                }
            }

            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    byte[] writeBuf = (byte[]) msg.obj;
                    int begin = (int)msg.arg1;
                    int end = (int)msg.arg2;

                    switch(msg.what) {
                        case 1:
                            String writeMessage = new String(writeBuf);
                            TextView fromDevice = (TextView) findViewById(R.id.fromDevice);
                            fromDevice.setText(writeMessage);
                            break;
                    }
                }
            };

            mConnectThread = new ConnectThread(mDevice, mHandler);
            mConnectThread.start();
        }
    });

    mSendText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText input = (EditText)findViewById(R.id.editText);

            if (input.getText() != null) {
                //for(int i = 0; i < mConnectedThread.length || i < 5; i++) {
                    String stringOutput = input.getText().toString();
                    byte[] mOutput = (byte[])stringOutput.getBytes();
                    Log.v("input", "input is: " + input);
                    Log.v("input", "input getText is: " + input.getText());
                    Log.v("input", "input getText toString is: " + input.getText().toString());
                    Log.v("input", "output is: " + mOutput.toString());
                    mConnectedThread.write(mOutput);
                //}
            }
        }
    });
}
private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
    private final Handler mHandler;
    private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

    public ConnectThread(BluetoothDevice device, Handler handler) {
        BluetoothSocket tmp = null;
        mHandler = handler;
        mmDevice = device;
        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mmSocket = tmp;
    }

    public void run() {
        mBluetoothAdapter.cancelDiscovery();
        try {
            mmSocket.connect();
        } catch (IOException connectException) {
            try {
                mmSocket.close();
            } catch (IOException closeException) {
                closeException.printStackTrace();
            }
            return;
        }

        mConnectedThread = new ConnectedThread(mmSocket, mHandler);
        mConnectedThread.start();
    }

    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}

and here is my ConnectedThread class:

class ConnectedThread extends Thread {
private       BluetoothSocket mmSocket;
private       Handler         mHandler;
private       InputStream     mmInStream;
private       OutputStream    mmOutStream;

public ConnectedThread(BluetoothSocket socket, Handler handler) {
    mmSocket = socket;
    mHandler = handler;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;
    try {
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    mmInStream = tmpIn;
    mmOutStream = tmpOut;
}

public void run() {
    byte[] buffer = new byte[1024];
    int begin = 0;
    int bytes = 0;
    while (true) {
        try {
            bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
            for(int i = begin; i < bytes; i++) {
                if(buffer[i] == "#".getBytes()[0]) {
                    mHandler.obtainMessage(1, begin, i, buffer).sendToTarget();
                    begin = i + 1;
                    if(i == bytes - 1) {
                        bytes = 0;
                        begin = 0;
                    }
                }
            }
        } catch (IOException e) {
            break;
        }
    }
}

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

public void cancel() {
    try {
        mmSocket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

Thank you!

  • Which line raises the `NullPointerException`? – rafaelc Feb 24 '16 at 03:04
  • Ah, duh. Should have included this. It's mConnectedThread.write(mOutput); , right before the inner ConnectThread class in the main class. – Ian Cunningham Feb 24 '16 at 03:05
  • in your connect thread if the connection fails, the error is not displayed, and the mConnectedThread is not created. You can trace it back by looking at which variable is null on the error line, and finding why the initialization is not performed when your think it should be. – njzk2 Feb 24 '16 at 03:20
  • @njzk2 I think this has something to do with it; when I connect android tries to connect for only a moment before closing the socket. – Ian Cunningham Feb 24 '16 at 03:23
  • suggestion: look at all your catch blocks and make sure there is a significative log in it. There is a good chance you have overlooked a completely different issue on that account – njzk2 Feb 24 '16 at 03:24

0 Answers0