I'm using the following code to grab images from the web. It uses Gridview and depending on position, picks a URL from an array. It works but the loading of images is often hit or miss. Almost every time I start the app, a different number of images load.
It also has issues when changing from portrait to landscape view, 5 out of 10 images may be displayed then I'll turn the device and usually lose all the images. Sometimes a few do show up though.
Any ideas on making this more robust?
try {
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream(开发者_JAVA技巧);
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
return bm;
} catch (IOException e) {
Log.d("DEBUGTAG", "error...");
}
return null;
One thing I read is that there's a known bug with decoding Bitmaps from an InputStream, and the suggested fix from Google was to use a FlushedInputStream (example in below URL):
http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html
Also, I'd put the download code into an AsyncTask. Here's what I currently use for mine:
public static Bitmap loadImageFromUri(URI uri)
{
URL url;
try {
url = uri.toURL();
} catch (MalformedURLException e) {
Log.v("URL Exception", "MalformedURLException");
return null;
}
try
{
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(new FlushedInputStream(input));
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
I just pass in a URI due to the way I've got the rest of my code set up, you could pass in a URL instead and skip the first part. This will keep the download from tying up your UI thread.
精彩评论