5

我正在开发一个 Android 应用程序,它的视图包含多个图库。画廊(位图)的内容是来自互联网的红色。

对于第一个画廊,一切正常,但是当尝试下载第二个画廊的第一个图像时,BitmapFactory.decodeStream(InputStream)返回 null,而流不为 null。

public void loadBitmap() throws IOException {

        for (int i = 0; i < images.size(); ++i) {
            URL ulrn = new URL(images.get(i).getThumbUrl());
            HttpURLConnection con = (HttpURLConnection) ulrn.openConnection();
            InputStream is = con.getInputStream();
            images.get(i).setImage(BitmapFactory.decodeStream(is));
            Log.i("MY_TAG", "Height: " + images.get(i).getImage().getHeight());
        }
}

返回图像的getThumbUrl()URL(例如http://mydomain.com/image.jpg)并NullPointerException在该行抛出 a Log.i("MY_TAG", "Height: ... )imagesArrayList我的类的包含对象,它也包含 URL 和位图)。

感谢您的任何建议!

4

3 回答 3

7

我遇到过这个。尝试将 BufferedHttpEntity 与您的输入流一起使用。我发现这可以防止 99.9% 的从 decodeStream 获取静默空值的问题。

也许并不重要,但我可靠地使用 org.apache.http.client.HttpClient 而不是 HttpURLConnection,如下所示:

public static Bitmap decodeFromUrl(HttpClient client, URL url, Config bitmapCOnfig)
{
    HttpResponse response=null;
    Bitmap b=null;
    InputStream instream=null;

    BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
    decodeOptions.inPreferredConfig = bitmapCOnfig;
    try
    {
    HttpGet request = new HttpGet(url.toURI());
        response = client.execute(request);
        if (response.getStatusLine().getStatusCode() != 200)
        {
            MyLogger.w("Bad response on " + url.toString());
            MyLogger.w ("http response: " + response.getStatusLine().toString());
            return null;
        }
        BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity());
        instream = bufHttpEntity.getContent();

        return BitmapFactory.decodeStream(instream, null, decodeOptions);
    }
    catch (Exception ex)
    {
        MyLogger.e("error decoding bitmap from:" + url, ex);
        if (response != null)
        {
            MyLogger.e("http status: " + response.getStatusLine().getStatusCode());
        }
        return null;
    }
    finally
    {
        if (instream != null)
        {
            try {
                instream.close();
            } catch (IOException e) {
                MyLogger.e("error closing stream", e);
            }
        }
    }
}
于 2011-05-09T19:26:30.683 回答
1

谷歌把我带到了这里。对于每个有同样问题的人:

问题: http ://code.google.com/p/android/issues/detail?id=6066

解决方案(“FlushedInputStream”): http ://android-developers.blogspot.com/2010/07/multithreading-for-performance.html

于 2011-10-06T08:06:52.680 回答
-1
public static Bitmap decodeStream (InputStream is)

退货

解码的位图,如果图像数据无法解码,则为 null。

您是否检查过您没有收到一些 404 错误或类似错误,而不是图像?

于 2011-05-09T18:58:10.577 回答