androidstringbyteandroid-bluetoothspp

Save Bytes from Seral Transfer to String


I have the following code and i'm trying to save the received bytes to a String until i receive \n.

 byte[] buffer = new byte[1024];
                int bytes;
                String ReceivedMessage = null;
                while (true) {

                    try

 {
                        // Read from the InputStream
                        bytes = mmInStream.read(buffer);

                        ReceivedMessage = ReceivedMessage + getString(bytes);
                        // Send the obtained bytes to the UI Activity
                        if(ReceivedMessage.endsWith("\\n")) {
                            String StringToReturn = ReceivedMessage.replace("\\n","");

                            Message msg = mHandler.obtainMessage(AbstractActivity.MESSAGE_READ);
                            Bundle bundle = new Bundle();
                            bundle.putString("Message", StringToReturn);
                            msg.setData(bundle);
                            mHandler.sendMessage(msg);

                            //mHandler.obtainMessage(AbstractActivity.MESSAGE_READ, bytes, -1, buffer)
                            //        .sendToTarget();
                        }

                } catch (IOException e) {
                    e.printStackTrace();
                    connectionLost();
                    BluetoothService.this.stop();
                    break;
                }

The problem is that it is crashing on ReceivedMessage = ReceivedMessage + getString(bytes);, more exactly on getString(bytes)

Can you help me to fix it?

Thanks!


Solution

  • String TempString = new String(buffer,0,bytes);
    ReceivedMessage = ReceivedMessage + TempString;