Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transfer huge data from servlet to android application

I am developing an android application in which i have to store a bitmap in a remote server. Steps are:

Step 1: Convert the bitmap into byte array and send it from android application to server.I am sending the bitmap as MultipartEntity.In server side, i am receiving it in doPost() method.

Step 2: Store the byte array in mysql database.Bitmap is stored as blob data type.I am able to store the received byte array into mysql database.

Step 3: Retrieve the bitmap stored as blob and send it back to the android application.I am able to retrieve the blob and convert into byte array and send it.

My Issue

The problem is the data sent from server is received in small batches.The image length was 1380 but it is received in variable lengths of 10's,50's,100's.When i add up the total i am getting only 1345,missing few bytes of data.I am posting the code in receiving end.

URL url = new URL( "http://10.0.2.2:8080/ServerPartProject/BlobGetter");
 URLConnection yc = url.openConnection();              
 BufferedReader in = new BufferedReader(new       InputStreamReader(yc.getInputStream()));                                                      String data;
 int val=0; 
 while((data=in.readLine())!=null){
    val=val+data.length();  //The data.length is like 10,20..
 }
 System.out.println("Total value obtained is "+val);//val was 1345 where it should be 1380

sending end:

OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
writer.write(senddata);

How to receive it in full stretch?

like image 296
androidGuy Avatar asked Apr 18 '26 01:04

androidGuy


2 Answers

Don't use readLine(). You are working with raw data. Raw data does not have lines only text has.

Some of your bytes are probably converted into 2 byte unicode characters which explains your perceived loss of data.

like image 51
mibollma Avatar answered Apr 19 '26 13:04

mibollma


I would avoid using the character-oriented Reader and Writer to send and receive image data (which is presumably in binary [if you are base64 encoding or something, which you don't mention, disregard this]). The bytes are being interpreted as characters, converted back to bytes, then interpreted as characters again, and finally back to bytes; in the process the image data is being corrupted. Use the InputStream/OutputStream interfaces supplied by the Http objects instead of putting Readers and Writers on them.

like image 33
antlersoft Avatar answered Apr 19 '26 14:04

antlersoft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!