Search code examples
javaandroidbufferblockingqueue

Creating a Buffer Class Using a Blocking Queue in Android


I am currently trying to implement a class to use as a buffer for incoming data over a bluetooth connection:

public class IncomingBuffer {

private static final String TAG = "IncomingBuffer";

private BlockingQueue<byte[]> inBuffer;

public IncomingBuffer(){
    inBuffer = new LinkedBlockingQueue<byte[]>();
    Log.i(TAG, "Initialized");
}

public  int getSize(){
    int size = inBuffer.size();
    byte[] check=new byte[1];
    String total=" ";
    if(size>20){
        while(inBuffer.size()>1){
            check=inBuffer.remove();
            total=total+ " " +check[0];
        }
        Log.i(TAG, "All the values inside are "+total);
    }
    size=inBuffer.size();
    return size;
}

//Inserts the specified element into this queue, if possible. Returns True if successful.
public boolean insert(byte[] element){
    Log.i(TAG, "Inserting "+element[0]);
    boolean success=inBuffer.offer(element);
    return success;
}

//Retrieves and removes the head of this queue, or null if this queue is empty.
public byte[] retrieve(){       
    Log.i(TAG, "Retrieving");
    return inBuffer.remove();

}

// Retrieves, but does not remove, the head of this queue, returning null if this queue is empty.
public byte[] peek(){

    Log.i(TAG, "Peeking");
    return inBuffer.peek();
}   
}

I'm having problems with this buffer. Whenever I add a byte array, all of the byte arrays in the buffer become the same as the one I just added.

I have tried using the same type of blocking queue within the rest of my code (without making it its own class), and it works fine. The problem seems to be when I use this class.

The way I declare the class is the following:

private IncomingBuffer ringBuffer;
ringBuffer = new IncomingBuffer();

Can anyone see where I am making a mistake?


Solution

  • It it possible that you are adding the same byte[] each time?

    Perhaps:

    public boolean insert ( byte[] element ) {
      Log.i(TAG, "Inserting "+element[0]);
      // Take a copy of the element.
      byte[] b = new byte[element.length];
      System.arraycopy( element, 0, b, 0, element.length );
      boolean success = inBuffer.offer( b );
      return success;
    }
    

    would solve your problem.