I am using Glide with RecyclerView to load many images (around 200) which have different sizes and dimensions.
I have three problems:
The images sometimes load successfully, and sometimes the app crashes giving OOM.
If the images are loaded successfully, then the scrolling is laggy.
If I refresh the layout and reload the same images, then it tries to load the images but fails before completion and gives OOM.
Following is the relevant code:
public static class MyViewHolder extends RecyclerView.ViewHolder {
@Override
public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {
ImageView imageView = holder.imageView;
Glide.with(imageView.getContext())
.load(tweetMapArray.get(listPosition).get("imageURL").toString())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.crossFade()
.into(imageView);
// imageURL is a valid URL for each item
}
@Override
public void onViewDetachedFromWindow(MyViewHolder holder) {
super.onViewDetachedFromWindow(holder);
Glide.clear(holder.imageView);
}
}
Please guide me as to what I am doing wrong. I have not worked with so many images before.
I have found the cause. The problem was that I was using NestedScrollView placed above RecyclerView. This was probably causing all images to load at once. I removed the NestedScrollView and requested around 200 images and it is working super smooth now.
Reference: Out Of Memory Error When loading more images in Glide
Thank you for writing replies. They are useful as well!
There is no easy way to determine what is causing your OutOfMemoryException
but there are ways to prevent it. Firstly, I would read this issue and then look into the Memory Monitor features of Android Studio to determine whether anywhere else in your app is causing a memory leak.
Then, I would look at some of the image sizes and whether you need to determine it necassary to crop the images when they are being binded. The .Override(width, height)
feature in Glide could assist you (width and height will be resized with pixels). Even further .centerCrop()
and .fitCenter()
could also help.
If that doesn't help at all, I would suggest adding a Load More feature. So you only initially load a small sample of images and the user can then load more from there using either a button, when they scroll to the bottom or SwipeRefreshLayout
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With