Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with Picasso OutOfMemoryError?

I want to show a ViewPager with ~50 pages, each containing a different image. Using Picasso, the first 20-25 pages work perfectly. However, at that point I get an OutOfMemoryError, and no images are loading at all:

Throwing OutOfMemoryError "Failed to allocate a 7477932 byte allocation with 1932496 free bytes"

I'm using the following code in my PagerAdapter:

@Override
public Object instantiateItem(final ViewGroup container, final int position) {
    View view = getView();
    Picasso picasso = getImageLoader(mContext);
    picasso.load(getUrl(position)).fit().into((ImageView) view.findViewById(R.id.imageview));
    container.addView(view);
    return view;
}

@Override
public void destroyItem(final ViewGroup container, final int position, final Object object) {
    container.removeView((View) object);
}

What can I do to avoid this?

like image 997
nhaarman Avatar asked Apr 21 '14 20:04

nhaarman


2 Answers

I have found this issue.

Some points noted:

  • Use skipMemoryCache()
  • Use builder.executor(Executors.newSingleThreadExecutor());
  • Use one instance of Picasso: do not create a new instance using Picasso.Builder every time.

I managed to fix my problem with the last one.

like image 85
nhaarman Avatar answered Sep 28 '22 03:09

nhaarman


This question is high ranked on Google hits, so I'm adding my solution to this problem.

Adding .fit() solved the problem for me. I'm successfully loading images with below code.

picasso.load(PartyUtil.getPartyIconResourceFromFullPartyName(parties.get(position)))
    .fit()
    .into(holder.icon);

Removing .fit() causes my application to throw an OutOfMemoryException.

like image 28
Marcus Avatar answered Sep 28 '22 04:09

Marcus