Why is this image bitmap not downloading in Android?
I have an appliation in which I have to download an image from an URL. I am using the following code for the same:
URL url = new开发者_运维百科 URL(address);
URLConnection conn = url.openConnection();
conn.connect();
int length = conn.getContentLength();
is = conn.getInputStream();
bis = new BufferedInputStream(is, length);
bm = BitmapFactory.decodeStream(bis);
The bm which is returned for some reason has height and width -1, and this is throwning Illegal state exception. What could be the reason that height and width is coming -1?
You should check what the length field returns. Most of these types of methods return -1 as the content length if the download failed
Please look below code
String url = server url;
InputStream ins = null;
try {
ins = new java.net.URL(url).openStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Bitmap b = BitmapFactory.decodeStream(new FlushedInputStream(ins));
imageview.setImageBitmap(b);
And used below function also
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;
}
}
精彩评论