How to clear input bufferStream

In the bluetoothChat application example, the data sent and received is added to an ArrayAdapter named mConversationArrayAdapter . There, each character is added to the array.

In my case, I have a row instead of an array, because I do not need to send and receive several data, I only need to send one row and each time I get one row.

The problem I get is that if I first get a string like hello world and then get a shorter one, the first one is overwritten by the second one and not the first one is deleted and the new one is written.

So, if I get hello world , and then I guess I need to get bye , then I really get byelo world .

So how can I flush the buffer every time I get what I want?

Code snipers

Send data:

  byte[] send1 = message_full1.getBytes(); GlobalVar.mTransmission.write(send1); 

Record a call:

 public void write(byte[] out) { /**Create temporary object*/ ConnectedThread r; /**Synchronize a copy of the ConnectedThread*/ synchronized (this) { if (GlobalVar.mState != GlobalVar.STATE_CONNECTED) return; r = GlobalVar.mConnectedThread; } /**Perform the write unsynchronized*/ r.write(out); } 

Create topic:

  public void write(byte[] buffer) { try { GlobalVar.mmOutStream.write(buffer); /**Share the sent message back to the UI Activity*/ GlobalVar.mHandler.obtainMessage(GlobalVar.MESSAGE_WRITE, -1, -1, buffer).sendToTarget(); } catch (IOException e) {} } 

Finally, read the "Subject":

  public void run() { byte[] buffer = new byte[12]; // buffer store for the stream int bytes; // bytes returned from read() /**Keep listening to the InputStream until an exception occurs*/ while (true) { try { /**Read from the InputStream*/ bytes = GlobalVar.mmInStream.read(buffer); /**Send the obtained bytes to the UI activity*/ GlobalVar.mHandler.obtainMessage(GlobalVar.MESSAGE_READ, bytes, -1, buffer).sendToTarget(); } catch (IOException e) { GlobalVar.mTransmission.connectionLost(); /**Start the service over to restart listening mode*/ //GlobalVar.mTransmission.start(); break; } } } 
+4
source share
1 answer

try it

 bytes = inputStream.read(buffer); buffer[bytes] = '\0'; 
0
source

Source: https://habr.com/ru/post/1495967/


All Articles