Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 996
Sandah Aung Avatar asked Apr 21 '15 13:04

Sandah Aung


People also ask

How do I cancel handler?

removecallback and handler = null; to cancel out the handle just to keep the code clean and make sure everything will be removed.

What happens to fragment when activity is destroyed?

As Fragment is embedded inside an Activity, it will be killed when Activity is killed. As contents of activity are first killed, fragment will be destroyed just before activity gets destroyed.

How do I remove runnable from Handler?

Just use the removeCallbacks(Runnable r) method.

What is an android handler?

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue . Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler it is bound to a Looper .


1 Answers

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 ();

}
like image 128
Murtaza Khursheed Hussain Avatar answered Oct 05 '22 08:10

Murtaza Khursheed Hussain