Search code examples
androidstringbytecharsequence

Not visualizing byte[] in snackbar


I am sending and receiving data from an android app to an arduino using the USB. The data I receive from the Arduino is in byte[] form:

UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
        @Override
        public void onReceivedData(byte[] arg0) {
            String data = null;
            try {
                data = new String(arg0, "UTF-8");
                displaySnackbar(data);
                data.concat("/n");
                tvAppend(textView, data);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    };

I am able to put all the data received in a TextView using the tvAppend method:

private void tvAppend(TextView tv, CharSequence text) {
    final TextView ftv = tv;
    final CharSequence ftext = text;

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            ftv.append(ftext);
        }
    });
}

But I cannot manage to put display the data on a Snackbar...

public void displaySnackbar(CharSequence data){
    View parentLayout = findViewById(R.id.activity_usb);

    data="hola "+data.toString()+ " end";
    Snackbar.make(parentLayout, data, Snackbar.LENGTH_LONG)

            .setAction("Action", null)
            .show();

How can i transform the data variable in order to be able to display it with a snackbar?

I feel like I'm missing something, but I don't know what... thanks in advance!


Solution

  • The answer was not related with the variable itself! The problem was related with the quantity of data receiving. The solution I have implemented uses a StringBuffer, which allows to display correctly the Strings!:

    private StringBuffer buffer = new StringBuffer();
    
    public void displaySnackbar(CharSequence text){
        final CharSequence ftext = text;
        View parentLayout = findViewById(R.id.activity_usb);
    
        buffer.append(ftext);
        Snackbar.make(parentLayout, buffer, Snackbar.LENGTH_LONG)
    
                .setAction("Action", null)
                .show();