Search code examples
javaandroidbluetoothruntime-errorindexoutofboundsexception

ArrayIndexOutOfBoundsException when read from buffer


My app send data (string or bytes) to another app copy via Bluetooth. I try to send big text or bytes[] and get this error:

FATAL EXCEPTION: Thread-8297
        java.lang.ArrayIndexOutOfBoundsException: length=1024; index=1024
            at com.ramimartin.multibluetooth.bluetooth.BluetoothRunnable.run(BluetoothRunnable.java:147)
            at java.lang.Thread.run(Thread.java:841)

So, why? Code from line

BluetoothRunnable.java:147

is:

while(bytesRead == bufferSize && buffer[bufferSize] != 0) {

Full code:

        int bufferSize = 1024;
        int bytesRead;
        byte[] buffer = new byte[bufferSize];
                    try {
                        if(this.mInputStream != null) {
                            bytesRead = this.mInputStream.read(buffer);
                            ByteBuffer bbuf = ByteBuffer.allocate(bytesRead);
                            if(bytesRead != -1) {
                                while(bytesRead == bufferSize && buffer[bufferSize] != 0) {
                                    bbuf.put(buffer, 0, bytesRead);
                                    if(this.mInputStream == null) {
                                        return;
                                    }

                                    bytesRead = this.mInputStream.read(buffer);
                                }

                                bbuf.put(buffer, 0, bytesRead);
                            }

                            EventBus.getDefault().post(new BluetoothCommunicatorBytes(bbuf.array()));
                            continue;
                        }
                    } catch (IOException var8) {
                        Log.e(TAG, "===> Error Received Bytes IOException  : " + var8.getMessage());
                        continue;
                    }

Solution

  • This should be:

    while(bytesRead == bufferSize && buffer[bufferSize - 1] != 0)
    

    Also there might be times when bufferSize is than 1.

    And the way to read an array is:

    int arr[] = new int[10];
    

    The max index in the above case will be:

    arr[9]
    

    as index starts from 0.