1

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!

2 Answers2

0

Editing this as I can't post comments:

You can only read a buffer once and

bytes = mmInStream.read(buffer);

reads the contents if indeed it's the same buffer. Hard to tell.

while(true) also means this will eventually trigger an exception.

[EDIT]

What's the stacktrace? What does getString call? Why are you using "while (true)" without any way out? Are you trying to read from the StreamBuffer twice?

(this would be a comment but haven't got enough rep)

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