Search code examples
androidandroid-recyclerviewmemory-leaksandroid-handler

How to avoid memory leaks in RecyclerView ViewHolder?


I have a RecyclerView with a header with a ViewPager. Since there is no way to make a ViewPager flip views automatically, I've added a runnable inside the ViewHolder to do so. So, the runnable keeps running even when another Activity is open and there is no way to stop it. The only moment when the runnable is when all the application is shut down.

For now, I have a runnable that creates a memory leak and runs all the time even when the other Activities opened. I've checked the Logcat and it seems the runnable no longer runs only once the Activity is destroyed.

handler.postDelayed(this, delay);

There is no way to call:

handler.removeCallbacks(runnable);

Is there a way to stop the runnable/any another way to flip the ViewPager?


Solution

  • So for example ...

    if you are using ViewPager inside RecyclerView then you should create method like

    public static void stopHandler(){
       handler.removeCallbacks(runnable);
    }
    
    public static void resumeHandler(){
       handler.postDelayed(runnable,DELAY_MS);
    }
    

    and call stopHandler in onPause/onDestroy and resumeHandler in onResume method.