Search code examples
androidandroid-viewpagerout-of-memoryuniversal-image-loader

JazzyViewPager + ImageLoading = OutOfMemory


I'm getting OutOfMemory error when I scroll through 70 or so images using JazzyViewPager.

There seems to be a bad memory leak somewhere in the Jazzy pager. I see it's holding on to the images even when i scroll way past them. Even on beefier devices I'm getting out of memory after scrolling through 70 images or so.

I'm using the universal-image-loader with this view pager, so not sure if that has anything to do with it.

Anyone else having this issue?


Solution

  • There is indeed a leak in JazzyViewPager.

    I ran a memory profiler and found that JazzyViewPager maintains a map of all the added views:

    private HashMap<Integer, Object> mObjs = new LinkedHashMap<Integer, Object>();
    
    public void setObjectForPosition(Object obj, int position) {
        mObjs.put(Integer.valueOf(position), obj);
    }
    

    It always adds objects, but never removes.

    To fix this, I added a remove method to the JazzyViewPager:

    public void removeObject(int position) {
        Object removed = mObjs.remove(position);
        if (removed != null) {
            LogUtils.LOGD(TAG, "Removed obj at pos " + position);
        }
    }
    

    and called it from my adapter's destroyItem():

    @Override
    public void destroyItem(ViewGroup container, int position, Object obj) {
        container.removeView(((JazzyViewPager)container).findViewFromObject(position));
    
        // make sure to remove the reference from the jazzyviewpager map
        ((JazzyViewPager)container).removeObject(position);
    }
    

    I monitored the memory usage and everything's fine now.