0

I have this, where mmInputStream is an InputStream of a Bluetooth connection:

    int bytes;
    boolean hasData;

    while (!isInterrupted()){

        byte[] buffer = new byte[1024];
        hasData = false;

        try {
            bytes = mmInStream.read(buffer);
            if (bytes > 0) {
                hasData = true;
            }
        } catch (IOException e){
            Log.d(TAG, e.getMessage());
            break;
        }

        if (hasData)  {
            final String data = new String(buffer).substring(0, bytes);
        }

In my monkey testing (with App/UI Exerciser) I got one of these:

java.lang.StringIndexOutOfBoundsException: length=1022; regionStart=0; regionLength=1024
    at java.lang.String.startEndAndLength(String.java:583)
    at java.lang.String.substring(String.java:1464)
    at com.mikehelland.omgbananasremote.BluetoothConnection.run(BluetoothConnection.java:80)

I don't see how that would even be remotely possible for the length of the buffer to end up less than what it was initialized as, every loop of the way.

Unless I totally don't understand Java, when I pass the buffer array to read(), it is by reference, and you can't change the size of an array, so read shouldn't be able to change the size of buffer in the code above. Right?

Anyone ever seen anything like this?

MikeHelland
  • 1,151
  • 1
  • 7
  • 17
  • I fixed the crash by checking the length of the string. I'm just really curious how the buffer size could have changed. – MikeHelland Feb 26 '18 at 01:49

1 Answers1

0

So even though the buffer was 1024 the resulting string was 1022, for maybe unicode reasons?

Anyways, as a comment suggested, String(buffer, 0, bytes) did the trick and no need for the substring().

MikeHelland
  • 1,151
  • 1
  • 7
  • 17