Volley has a built-in method to fit the image to a given width and height, as you mentioned. You need to stop using the convenient image loading methods provided by NetworkImageView that don't use it. I suggest using the following methods to reduce the chance of OOM errors:
- Stop using
NetworkImageView . Use a regular ImageView and implement a listener to apply the image when it is available. This is a prerequisite for step 2. Using the NetworkImageView method with the get() method can lead to problems in my experience. " - Create an
ImageLoader and use the get() method that gets the ImageRequest . Use an optional constructor that takes maxHeight and maxWidth as parameters, if you can. - When you use the previously mentioned
get() method in ImageLoader , save the ImageContainer link that the method returns so that you can cancel the request if the view has been processed before the request completes. - Provide a good implementation for
ImageCache in the ImageLoader constructor. This will reduce redundancy in decoding bitmaps that are already available. - If your architecture allows this, try using the
recycle() method for bitmaps, but be careful not to recycle the ones you still need.
EDIT: Added code examples
Code snippet for (2) + (4)
// assuming sRequestQueue is your static global request queue // and `BitmapCache` is a good implementation for the `ImageCache` interface sImageLoader = new ImageLoader(sRequestQueue, new BitmapCache());
Code snippet for (3) if the ViewHolder and ImageContainer template is a member of the ViewHolder class. The principle applies to any architecture.
// when applying a new view cancel the previous request first if (imageContainer != null) { imageContainer.cancelRequest(); } // calculate the max height and max width imageContainer = sImageLoader.get(imageUrl, new DefaultImageListener(image), maxWidth, maxHeight);
The default image downloader (you can do what you are here):
private class DefaultImageListener implements ImageListener { private ImageView imageView; public DefaultImageListener(ImageView view) { imageView = view } @Override public void onErrorResponse(VolleyError error) {
source share