JTextField is updating String data along with junk

83 Views Asked by At

I'm trying to update received ByteBuffer data (converted to String) to JTextField, but text field is printing output data along with junk values, even after trimming the string.

But in output console it is printing proper data, when it comes to text field in GUI it's printing junk data along with proper data.

import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;

public class UsbRead
{
    static final byte IN_ENDPOINT1 = (byte) 0x82;
    static final int TIMEOUT = 100;
    static final byte INTERFACE = 1;
    static final byte interfaceNum = 1;
    static String s=new String();
    static String dd=new String();

    public static String read(DeviceHandle handle) 
    {
        try{
            System.out.println("-----read-----");
            ByteBuffer buffer = BufferUtils.allocateByteBuffer(30);
            IntBuffer transferred = BufferUtils.allocateIntBuffer();
            System.out.println("capacity-->"+buffer.capacity());
            int result=LibUsb.bulkTransfer(handle, IN_ENDPOINT1, buffer, 
           transferred, TIMEOUT);
            if (result != LibUsb.SUCCESS)
            {
                throw new LibUsbException("Unable to read data", result);
            }
            else
            {
                System.out.println("---------------------------read----------");
                System.out.println(transferred.get() + "-------- bytes read from device");
                s="";
                s = StandardCharsets.UTF_8.decode(buffer).toString();
                System.out.println("s--"+s);
                s.trim();
                WisePanel4.textField_1.setText(s);
                dd=s;
                System.out.println("received data ->"+dd);
            }
            return dd;
        }
        catch(Exception e)
        {
            System.out.println("-*----read time out");

        }
        return dd;
    }
}

output -->

---------------------------read----------

20-------- bytes read from device

s--192.168.1.108

received data ->192.168.1.108

Please check the image of GUI. It is printing junk value with proper data:

enter image description here

1

There are 1 best solutions below

1
On BEST ANSWER

Most probably you are receiving a C-String as a response. So the String is terminated by a NUL ('\0') character. Try getting the value using:

s = s.substring(0, s.indexOf('\0'));