Search code examples
javaandroidandroid-fragmentshandlerandroid-adapter

How to remove Handler from adapter


I am using a function into an adapter and I added a Handler to do the refresh every 2s like below:

 final Handler refreshHandler = new Handler();
 Runnable runnable = new Runnable() {
     @Override
     public void run() {
         refreshHandler.postDelayed(this, 2000);
         myfunction();
     }
 };
 refreshHandler.postDelayed(runnable, 2000);

When I'm not into the fragment where I deploy the adapter the handler is always reloading.

So my question is, how to stop the handler every time I quit the fragment?


Solution

  • I think you should use the removeCallbacks(Runnable r) method.

    That's how you put it in your code:

          final Handler refreshHandler = new Handler();
     Runnable runnable = new Runnable() {
         @Override
         public void run() {
             refreshHandler.postDelayed(this, 2000);
             myfunction();
         }
     };
     refreshHandler.postDelayed(runnable, 2000);
    
    
    @Override
    public void onDestroy () {
    
        refreshHandler.removeCallback(runnable);
        super.onDestroy ();
    
    }
    

    Something like that wherever you want. Hope you understand