0

I am making an android application that can communicate with arduino serially over USB and used UsbSerial library from Github. I'm receiving data from arduino in UsbReadCallback which I have implemented as:

 private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
        @Override
        public void onReceivedData(byte[] arg0) {
            try {
                String data = new String(arg0, Charset.forName("utf-8"));
                if (mHandler != null)
                {
                    mHandler.obtainMessage(0, data).sendToTarget();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

and my Handler as:

private static class MyHandler extends Handler {

    private final WeakReference<SensorDisplayActivity> mActivity;

    public MyHandler(SensorDisplayActivity activity) {
        mActivity = new WeakReference<>(activity);

    }

    @Override
    public void handleMessage(Message msg) {

             String   data = ( String) msg.obj;
        mActivity.get().mainValue_tx.setText(data);


    }
}

But problem arriving when I'm displaying it in the TextView using setText() its not showing the correct value i.e. sometimes showing 00 in place of 100 and 2 in place of 42 etc. but when I'm using append() method of TextView the correct values are appending correctly. What might be the solution?

  • The solution is just to concatenate the chunks together until you have an original message. Its quite normal under TCP that messages come in fragmented. – greenapps Dec 31 '16 at 17:47
  • If i want to receive random values how can i make sure i received the original message? – Saurabh Badola Dec 31 '16 at 17:58
  • Sorry but i do not understand what you want to receive. Random values? Whats that? Nor what is sent exactly. – greenapps Dec 31 '16 at 18:38
  • I am sending some random values that i want to receive but in casr – Saurabh Badola Dec 31 '16 at 19:10
  • You can't use 'random values' - there has to be some way for the recipient to work out from the data being sent where one message (value) ends and the next one starts. For example you could use a linefeed \n character (as long as this could not occur in the data itself) or each message could begin with an additional byte which is the length 0-255 of the message (value) - or come up with another way of doing it. Then as @greenapps says, accumulate data until you have a complete message you can decode. – DisappointedByUnaccountableMod Jan 01 '17 at 19:29

0 Answers0