i know this was handled a lot here, but i couldnt solve my problem yet: I read bytes from a Parceble Object and save them in a byte[], then I unmurshall them back to an Object an it works all fine. But i have to send the bytes as a String, so i have to convert the bytes to string and then return.
I thought it would work as follow:
byte[] bytes = p1.marshall(); //get my object as bytes
String str = bytes.toString();
byte[] someBytes = str.getBytes();
But it doesnt Work, when I "p2.unmarshall(someBytes, 0, someBytes.length);" with someBytes, but when I p2.unmarshall(bytes, 0, bytes.length); with bytes, it works fine. How can i convert bytes to String right?
You've got three problems here:
toString()
on byte[]
, which is just going to give you something like "[B@15db9742"
getBytes()
without specifying the character encoding, which is almost always a mistake.In this case, you should just use base64 - that's almost always the right thing to do when converting arbitrary binary data to text. (If you were actually trying to decode encoded text, you should use new String(bytes, charset)
, but that's not the case here.)
So, using android.util.Base64
:
String str = Base64.encodeToString(bytes, Base64.DEFAULT);
byte[] someBytes = Base64.decode(str, Base64.DEFAULT);
See more on this question at Stackoverflow