Search code examples
androidimageandroid-recyclerviewpicasso

OutOfMemoryError while loading images


I'm working on a project that uses a series of image urls and loads them into a recyclerview grid. The images can be any resolution and the app crashes after loading just 6 images. I thought using Picasso would solve the problem but that didn't work. The app is now slower and recyclerview scroll is laggy while it loads only 3-4 images at max before crashing.

Memory Leaks:

    public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
    LayoutInflater inflater;

    public RecyclerViewAdapter(Context c){
        inflater=LayoutInflater.from(c);
    }

    @NonNull
    @Override
    public RecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = inflater.inflate(R.layout.recyclerview_item,parent,false);
        itemView.setMinimumHeight(150);
        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
        if(urls!=null){
        //Uri uri = Uri.parse(urls.get(position));
        //Toast.makeText(getContext(),""+urls.get(position),Toast.LENGTH_SHORT).show();
        Picasso.with(context)
                .load(urls.get(position))
                .into(holder.view);
        }
    }

    @Override
    public int getItemCount() {
        if(urls != null)
            return urls.size();
        else
            return 0;
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        ImageView view;

        public ViewHolder(View itemView) {
            super(itemView);
            view=itemView.findViewById(R.id.image_recycler);
        }

        @Override
        public void onClick(View v) {

        }
    }
}

Solution

  • This is from Picasso official website, it'll reduce the image size. If this works then the problem is that your images sizes are too big

    You can also specify custom transformations for more advanced effects.

    public class CropSquareTransformation implements Transformation {
      @Override public Bitmap transform(Bitmap source) {
        int size = Math.min(source.getWidth(), source.getHeight());
        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;
        Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
        if (result != source) {
          source.recycle();
        }
        return result;
      }
    
      @Override public String key() { return "square()"; }
    }
    

    Pass an instance of this class to the transform method.