Picasso: out of memory

后端 未结 4 1537
名媛妹妹
名媛妹妹 2020-12-08 14:34

I have a RecyclerView presenting several images using Picasso. After scrolling some time up and down the application runs out of memory with messag

4条回答
  •  失恋的感觉
    2020-12-08 14:43

    I just made a Singleton class to LoadImages. The problem was that I was using too many Picasso objects created with too many Picasso.Builder. Here's my implementation:

    public class ImagesLoader {
    
        private static ImagesLoader currentInstance = null;
        private static Picasso currentPicassoInstance = null;
    
        protected ImagesLoader(Context context) {
            initPicassoInstance(context);
        }
    
        private void initPicassoInstance(Context context) {
            Picasso.Builder builder = new Picasso.Builder(context);
            builder.listener(new Picasso.Listener() {
                @Override
                public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
                    exception.printStackTrace();
                }
            });
            currentPicassoInstance = builder.build();
        }
    
        public static ImagesLoader getInstance(Context context) {
            if (currentInstance == null) {
                currentInstance = new ImagesLoader(context);
            }
            return currentInstance;
        }
    
        public void loadImage(ImageToLoad loadingInfo) {
            String imageUrl = loadingInfo.getUrl().trim();
            ImageView destination = loadingInfo.getDestination();
            if (imageUrl.isEmpty()) {
                destination.setImageResource(loadingInfo.getErrorPlaceholderResourceId());
            } else {
                currentPicassoInstance
                        .load(imageUrl)
                        .placeholder(loadingInfo.getPlaceholderResourceId())
                        .error(loadingInfo.getErrorPlaceholderResourceId())
                        .into(destination);
            }
        }
    }
    

    Then you create an ImageToLoad class that holds the ImageView, Url, Placeholder and Error Placeholder.

    public class ImageToLoad {
    
        private String url;
        private ImageView destination;
        private int placeholderResourceId;
        private int errorPlaceholderResourceId;
    
        //Getters and Setters
    
    }
    

提交回复
热议问题