问题描述
我开发一个Android应用程序,它的观点是包含多个Gallerys。在Gallerys(位图)的含量是红从互联网上。
I'm developing an Android application, and it's view is containing multiple Gallerys. The content of the Gallerys (the Bitmaps) are red from the Internet.
对于第一个画廊,一切工作正常,但试图下载第二画廊的第一个图像时, BitmapFactory.de codeStream(InputStream中)
返回空,而流不为空。
For the first gallery, everything works fine, but when trying to download the first image of the second Gallery, the BitmapFactory.decodeStream(InputStream)
returns null, while the stream is NOT 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异常
在该行 Log.i(MY_TAG,身高:...)
(图片
是我的课,保存URL和位图过的的ArrayList
包含对象)。
The getThumbUrl()
returns the URL of the image (eg. http://mydomain.com/image.jpg)and it throws a NullPointerException
at the line Log.i("MY_TAG", "Height: ... )
(images
is an ArrayList
containing objects of my class, that holds the URL and the Bitmap too).
感谢您的任何意见!
推荐答案
我已经运行到这一点。尝试使用BufferedHttpEntity你的InputStream。我发现这个prevented 99.9%的问题得到沉默的空值从去codeStream。
I've run into this. Try using BufferedHttpEntity with your inputstream. I found this prevented 99.9% of the issues with getting silent nulls from decodeStream.
也许不是signficant,但我确实用org.apache.http.client.HttpClient而不是HttpURLConnection类如:
Maybe not signficant, but I reliably use org.apache.http.client.HttpClient rather than HttpURLConnection as in:
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);
}
}
}
}
这篇关于BitmapFactory.de codeStream(InputStream的是)返回在Android上非空的InputStream空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!