androidlistviewandroid-fragmentsandroid-lifecyclefragment-lifecycle

Stop handler after the fragment has been destroyed


I have a Fragment which sets up a ListView and creates a Handler to update the Listview periodically. However, it looks like the Handler still runs after the Fragment has been destroyed.

The following is the code.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    //boilerplate code

    final Handler handler = new Handler();
    handler.post(new Runnable() {
        @Override
        public void run() {
            assignAdapter();
            handler.postDelayed(this, 15000);
        }
    });

    return v;
}

Updating the ListView after the destruction of the Fragment causes the app to crash. How can I cause the Handler to stop as the Fragment gets destroyed? I would also like to know what effects if any pausing the app has on the Handler as well.


Solution

  • You need to implement handler like this

    private Handler myHandler;
    private Runnable myRunnable = new Runnable() {
        @Override
        public void run() {
            //Do Something
        }
    };
    
    @Override
    public void onDestroy () {
    
        mHandler.removeCallbacks(myRunnable);
        super.onDestroy ();
    
    }