0

I'm writing some simple networking code which involves working with ByteBuffers. For some reason, the following code throws an UnsopportedOperationException on two of my test devices:

int send = Integer.parseInt(edtxt.getText().toString());

OutputStream out = sock.getOutputStream();

ByteBuffer buf = ByteBuffer.allocateDirect(1);
buf.order(ByteOrder.BIG_ENDIAN);
    buf.put((byte)send);
    buf.rewind();
byte[] outa = buf.array(); //Exception thrown here
out.write(outa);

The two devices it fails on are:

  • Sony Ericsson Xperia Play running Android 2.3.3

  • Motorla Droid X2 running Android 2.3.5

The two it works on are:

  • LG G3 running Android 4.4.2

  • Nexus 4 running Android 4.4.4

The docs say that UnsupportedOperationException will be thrown if the byte buffer isn't based on an array. Is this a difference between Gingerbread and KitKat that I just need to deal with, or is it just a case of bad practice?

AlexRamallo
  • 637
  • 1
  • 5
  • 23

1 Answers1

0

If figured it out the other day shortly after I posted this question, but was going to wait for someone with a better explanation than I. Since no one has posted anything yet I'll just do it myself.

The key to making the above code work on all 4 test device was to use ByteBuffer.allocate instead of allocateDirect. I'm not exactly sure why the latter does not guarantee an array backing for the buffer though. I did find this answer: https://stackoverflow.com/a/5671880/482085 482085

Which gives a good explanation of the differences between the two allocation methods. Apparently, a direct buffer is mapped to native OS memory outside of the JVM. If I had to guess as to why this resulted in no array backing for my Gingerbread devices, it could have something to do with the devices having significantly less overall memory avilable than my KitKat devices (although as you can see in my code snippet, the byte buffer is not large at all)

I guess you could try both if you really want to have a direct buffer, and use exception handling in case a direct allocation fails.

If anyone needs a solution to the above problem, this should suffice. However I still don't have a real answer for the underlying issue.

Community
  • 1
  • 1
AlexRamallo
  • 637
  • 1
  • 5
  • 23