Search code examples
javaandroidbluetoothinputstream

Is there a way to decode InputStream data to text without using a Stream Decoder on the InputStream Object itself?


I have made a Bluetooth InputStream listener that checks whether there is incoming data simply by asking if(InputStream.isAvailable > 0), then created a loop to store the incoming data into an int[] until there is no more and it works perfectly. I'm using a simple Log.d logger to output the result. I'm still a beginner and can understand basic concepts. The text that is being sent through my bluetooth device to my phone is "Hello Android!", but It's encoded into integers and I would like to convert the int[] to String so that I can get the encoded text without having to use a Stream Decoder, but the integers. Is it possible? The actual output working as intended looks like this: 72, 101, 108, 111, 32, 65, 110, 100, 114, 111, 105, 100, 33, 13, 10,. All of them don't arrive at the same time, of course, because they are being sent one by one and that is nothing to worry about because I will use my own delimiters to determine start and end of one whole data.

My code:

if(mmInputStream.available() > 0) {

    int[] receivedBytes = new int[1024];
    int i = 0;

    while(mmInputStream.available() > 0) {
        receivedBytes[i] = mmInputStream.read();
        i++;
    }

    String s = "";

    for(int j = 0; j < i; j++){
        s += receivedBytes[j] + ", ";
    }

    Log.d("INPUTSTREAM_DATA", s);

}

The reason why I did it this way is to immediately output the incoming data as soon as one session of data is sent.


Solution

  • Horrible code. Do NOT use the single character read function like that- this is hugely inefficient. Decide on a buffer size and use the byte array version. You can then convert an entire byte array to a string via new String(array, encoding) where encoding is the encoding of your data (UTF-8, UTF-16, etc).

    And do not use + to concatenate strings like that- Strings are immutable so each use causes a new object to be created. Use a StringBuilder instead. Better code would look like this (ignoring required Exception handling)

    int BUFFER_SIZE = 1024;
    StringBuilder builder = new StringBuilder();
    byte data[] = new byte[BUFFER_SIZE];
    while(inputStream.available() > 0) {
       int read = inputStream.read(data);
       builder.append(new String(data, 0, read, "UTF-8"));
    }
    return builder.toString();