Why is this bitmap not loading on Android?

I have an application in which I need to download an image from a URL. For this, I use the following code:

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); 

Returned for some reason, bm has a height and width of -1, and this eliminates an exception from the illegal state. What could be the reason that the height and width are approaching -1?

0
source share
2 answers

You should check what the length field returns. Most of these types of methods return -1 as the length of the content if the download fails.

+1
source

Please see 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 the function used below is 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; } } 
+1
source

All Articles