Cannot load image from a Url using BitmapFactory.decodeStream()

我是研究僧i 提交于 2019-12-06 06:06:50

The problem was in the BitmapFactory.decodeStream() method. It seems that this method has a bug that makes it fail on slow connections. I applied the recommendations found at http://code.google.com/p/android/issues/detail?id=6066.

I created the FlushedInputStream class below:

public class FlushedInputStream extends FilterInputStream {

protected FlushedInputStream(InputStream in) {
    super(in);
}

@Override
public long skip(long n) throws IOException {
    long totalBytesSkipped = 0L;
    while (totalBytesSkipped < n) {
        long bytesSkipped = in.skip(n - totalBytesSkipped);
        if (bytesSkipped == 0L) {
              int onebyte = read();
              if (onebyte < 0) {
                  break;  // we reached EOF
              } else {
                  bytesSkipped = 1; // we read one byte
              }
       }
        totalBytesSkipped += bytesSkipped;
    }
    return totalBytesSkipped;
}
}

Then, in my code I used:

bm = BitmapFactory.decodeStream(new FlushedInputStream(entity.getContent()));

instead of:

bm = BitmapFactory.decodeStream(new BufferedInputStream(entity.getContent()));
OleGG

Try to wrap your HttpEntity into BufferedHttpEntity, like it's done in this question: BitmapFactory.decodeStream returns null without exception . Seems that problem is quite similar.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!