How to Clear byte buffer in android

3.2k Views Asked by At

I am doing an application that consists of a sending an receiving data from android to the micro controller here in the receiving side that was from micro-controller to the android i was using a byte buffer to store the data.But here i got a problem i want to receive data of multiple bytes at different stages for this i want to clear the byte buffer and re-use the same byte buffer again can any one tell me how to clear the byte buffer

This is my receiving code:

ByteBuffer buffer = ByteBuffer.allocate(64);
         byte[] length = buffer.array();
         byte[] Recevied_Data = new byte[64];
         UsbRequest request = new UsbRequest();

         while (true) 
         {
            request.initialize(UsbDriver.USB_Device_Connection, UsbDriver.Data_In_End_Point); 
            request.queue(buffer, 64);
             if (UsbDriver.USB_Device_Connection.requestWait() == request) 
             {
                for(int i=0;i<length.length;i++)
                {   
                    Recevied_Data[i]=buffer.get(i);
                    if(Recevied_Data[0]==0x02 && Recevied_Data[1]==0x3B && Recevied_Data[2]==0x3B && Recevied_Data[3]==0x00 && Recevied_Data[4]==0x03){
                    Communication_Ok=true;
                //  **I want to clear the Buffer Here**           


                }
             }

             }
         } 
2

There are 2 best solutions below

0
On

This might be enough. BUT if you want to erase the data completely, you could Look here,though it's dirty but simple and readble.

0
On

Why do you want to erase the data ? Is it local variable ? If it is local variable any way it will be cleared by GC otherwise(in case of member variable) just assign null to buffer. You can do memset by copying 0(using arraycopy) to bytebuffer but it will be pointless code.