Download Image from url is sometimes returning null image
I am using the following code to download a bitmap from a url,:
myFileUrl = new URL(fileUrl); HttpURLConnection conn = (HttpURLConnection) myFileUrl .openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); Bitmap bmpTemp = BitmapFactory.decodeStream(is);
bu开发者_C百科t sometimes, I mean once in a hundred times, the bitmap is null! any body knows what might be the problem,
Thanks
There is a bug in the url connection. It has a fix that uses a FlushedInputStream decorator function for it. here is the code for it:
/*
* An InputStream that skips the exact number of bytes provided, unless it reaches EOF.
*/
public static class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
@Override
public long skip(long n) throws IOException {
long totalBytesSkipped = 0L;
while (totalBytesSkipped < n) {
long bytesSkipped = in.skip(n - totalBytesSkipped);
if (bytesSkipped == 0L) {
int b = read();
if (b < 0) {
break; // we reached EOF
} else {
bytesSkipped = 1; // we read one byte
}
}
totalBytesSkipped += bytesSkipped;
}
return totalBytesSkipped;
}
}
the usage is:
BitmapFactory.decodeStream(new FlushedInputStream(is));
精彩评论