Search code examples
androidpicassoimageswitcher

Using Picasso library with ImageSwitcher is causing Object out of Memory errors


I want to load large bitmaps efficiently in my Image Switcher and i have been using Picasso for this purpose but now i am stuck at this point. Without Picasso a lot of OOMs and other nasty exceptions please tell me if I can use this library with Image Switcher too. If yes then provide sample code.

Thanks!

imswitch.setFactory(new ViewFactory() {

        @Override
        public View makeView() {
              ImageView imageView = new ImageView(getApplicationContext());
              imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
              imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
              return imageView;
        }
    } );

And onClick:

     btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
               currentIndex++;
               // If index reaches maximum reset it
                if(currentIndex==messageCount)
                    currentIndex=0;
                ImageView imageView = (ImageView)findViewById(R.id.imswitch);
                Picasso.with(getApplicationContext()).load(imageIds[currentIndex]).into(imageView);
                Toast.makeText(getApplicationContext(), "Pressed "+currentIndex,Toast.LENGTH_LONG).show();
        }

Solution

  • One of the possible way is to create own implementation using Target interface.

    https://square.github.io/picasso/javadoc/com/squareup/picasso/Target.html

    public class ImageSwitcherPicasso implements Target {
    
            private ImageSwitcher mImageSwitcher;
            private Context mContext;
    
            public ImageSwitcherPicasso(Context context, ImageSwitcher imageSwitcher){
                mImageSwitcher = imageSwitcher;
                mContext = context;
            }
    
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
                mImageSwitcher.setImageDrawable(new BitmapDrawable(mContext.getResources(), bitmap));
            }
    
            @Override
            public void onBitmapFailed(Drawable drawable) {
    
            }
    
            @Override
            public void onPrepareLoad(Drawable drawable) {
    
            }
    
        }
    

    Than just use as follow

    
    
        ImageSwitcherPicasso mImageSwitcherPicasso = new ImageSwitcherPicasso(getActivity(), playerBackground);
        Picasso.with(getActivity()).load(new File(path)).into(mImageSwitcherPicasso);
    
    
    

    where playerBackground is reference to ImageSwitcher