3

I created an Object which is sent through Google Cloud Endpoints. Among its parameters there is one parameter of type byte[] with its getter and setter methods.

The problem is when I want to set the byte[] parameter in my app it expects somehow a parameter of type String? Does it want me to encode the byte array or what is the reason for that strange error?

When I get the parameter from the dataObject it is of type byte[] and everything is fine. I am really confused!

My Object is DataPackage defined in my Backend

 ...
 private byte[] imageThumbnail;

 public void setImageThumbnail(byte[] imageThumbnail) {
    this.imageThumbnail = imageThumbnail;
}

public byte[] getImageThumbnail() {
    return imageThumbnail;
}

Then in my app I try to set the imageByteArray

 dataPackage.setImageThumbnail(byteThumbnail); // gives error that String is expected

And this works fine

 dataPackage.getImageThumbnail() // is of type byte[]
  • 1
    Could you post the relevant code and any related LogCat messages printed out? – Jay Snayder Jan 09 '15 at 20:23
  • I'm faced the same problem. Did you solve it ? – serj Mar 26 '15 at 14:01
  • 1
    I solved it by not using the datastore to save images at all. You could use the endpoints to send images when you decode them to a Base64 String but sooner or later you will find out that it takes a lot of time(1 Mb ~ 10 Seconds) to up or download the image. I recommend to use the Blobstore with a Servlet for any images it's way more faster and not in your Upload/Download Qouta! – Marcel_marcel1991 Mar 28 '15 at 20:04

2 Answers2

2

While it may not be your first choice, is it possible to use the byte[] constructor for a string and pass it that? An example of how to do so can be found here

Essentially the relevant part of that question/answer is this:

byte[] b = {(byte) 99, (byte)97, (byte)116}; //This could also be your byte array
String s = new String(b, "US-ASCII"); // US-ASCII might need to be something else

and then the opposite process:

String s = "some text here"; //The string from dataPackage.getImageThumbnail()
byte[] b = s.getBytes("UTF-8"); //Might need to be some other byte formatting 

Happy coding! Leave a comment if you have any questions.

Community
  • 1
  • 1
Matt
  • 5,404
  • 3
  • 27
  • 39
  • Good useful information, though it does not address the OP question. It is kind of sad that the best answer Marcel found to what seems a simple question was `don't do that`. – Jesse Chisholm Apr 14 '17 at 16:58
-1

You should decode and encode using the Base64 class of from the Android framework.

String encodedBitArray = Base64.encodeToString(imageThumbnail, Base64.DEFAULT);

byte[] decodedArray = Base64.decode(encodedBitArray, Base64.DEFAULT);

If you want to convert the byte array to a Bitmap you need to do the following :

Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

SO example

Community
  • 1
  • 1
serj
  • 508
  • 4
  • 20