mttkay / ignition

Kick-starts Android application development.
1.28k stars 290 forks source link

Image is blank after download is finished #29

Open yifengj opened 12 years ago

yifengj commented 12 years ago

I found a bug in ignition-support library when using RemoteImageLoader to downloading images. Some images will not download correctly after finished downloading, especially on some mobile networks.

The root cause is in these lines in RemoteImageLoaderJob.java: int fileSize = connection.getContentLength(); ... byte[] imageData = new byte[fileSize];

            int bytesRead = 0;
            int offset = 0;
            while (bytesRead != -1 && offset < fileSize) {
                bytesRead = istream.read(imageData, offset, fileSize - offset);
                offset += bytesRead;
            }

According to Android documentation of HttpURLConnection, "By default, this implementation of HttpURLConnection requests that servers use gzip compression. Since getContentLength() returns the number of bytes transmitted, you cannot use that method to predict how many bytes can be read from getInputStream().".

So when compression in use, getContentLength() will return bytes less than the total size of image data.

amar08007 commented 12 years ago

Hi,

I went through the original code and the solution which has been provided in #30. I have come up with this solution which I think will work for all the cases. What I have done is that I used a flag named disableCompression which will be passed in the construction. We calculate the file size using getContentLength() and it comes out to be greater than 0 and the disableCompression is true then I have disabled the compression (connection.setRequestProperty("Accept-Encoding", "identity")) as mentioned on the documentation for HTTPURLCONNECTION and used the code which was earlier in the else part. And if any of the two conditions are not satisfied, then I have used the code which was used to get data of unknown length.

Please go through the attached patch file and let me know if I this is correct or if it contains any mistakes. This is my first contribution to open source so please pardon me for any errors (I have tried my best to minimize those).

patch file : https://gist.github.com/3084469

Thanks