felHR85 / UsbSerial

Usb serial controller for Android
MIT License
1.81k stars 589 forks source link

How to clear data from object after receiving data from serial device, so that i can receive the next data? #293

Closed ShashiShekhar7 closed 3 years ago

ShashiShekhar7 commented 4 years ago

String data; static StringBuilder str = new StringBuilder();

/*
 *  Data received from serial port will be received here. Just populate onReceivedData with your code
 *  In this particular example. byte stream is converted to String and send to UI thread to
 *  be treated there.
 */
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {

    @Override
    public void onReceivedData(final byte[] arg0) {

                try {
                    for (byte b : arg0) {
                        String st = String.format("%02X", b); //Convert Byte to hex
                        str.append(st);
                        data = str.toString();
                    }

                    if (mHandler != null){
                        mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, data).sendToTarget();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
    }
};
AblertEinstein commented 3 years ago

You can use the function str.delete(0, str.length()) to clear the data after the for loop.

ShashiShekhar7 commented 3 years ago

Thanks for the reply. It was a silly question. It was solved on the same day I asked. But forgot to close the issue.