0

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?

Sathyajith Bhat
  • 21,321
  • 22
  • 95
  • 134
user590849
  • 11,655
  • 27
  • 84
  • 125

2 Answers2

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

zienkikk
  • 2,404
  • 1
  • 21
  • 28
1

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;
    }
}
Nikhil
  • 16,194
  • 20
  • 64
  • 81
  • what does src name refer to here. i can put anything? the documentation is not clear on this... – user590849 Jun 24 '11 at 05:41
  • Please check link http://stackoverflow.com/questions/6122599/android-drawable-createfromstreamis-srcname-whats-the-2nd-parameter-meaning – Nikhil Jun 24 '11 at 06:01
  • thanks for your response but the code that you have given is not working. sometimes the drawable comes null from the source and sometimes even if it does when i set it by setImageDrawable().. an exception is being thrown. – user590849 Jun 24 '11 at 06:14
  • please check answer i have update it i think it is more helpful to you. – Nikhil Jun 24 '11 at 06:18
  • any query then let me know. if you find this is helpful then right answer and upvote it so more help to other also. – Nikhil Jun 24 '11 at 06:28
  • nopes the server that i was downloading from has creashed for some reason. hence have not been able to try it. thanks though. i will get back to you as soon as i done downloading. – user590849 Jun 24 '11 at 14:26