4

I encountered an unusual NPE exception in Android with handler and background thread.

I know when the activiy or fragment on destroy, the ui widget will be destroied, so you must cancel all the pending message or runnable sent from the background.

For example, in the fragment callback onDestroyView, i call handler' s removeCallbacksAndMessages(null) to remove all the callbacks. But, in some case, the callback still got executed, but at that time the ui has been destroied, the NPE throws.

Below is the sample:

public class SampleFragment extends Fragment {
  private Handler mHandler = new Handler() {
    @Override public void handleMessage(Message msg) {
      switch (msg.what) {
        // do your job
      }
    }
  };

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // create some ui
    return super.onCreateView(inflater, container, savedInstanceState);
  }

  @Override public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    new Thread(new Runnable() {
      @Override public void run() {
        // after a long running work
        mHandler.post(new Runnable() {
          @Override public void run() {
            // OOPS, the ui widget may null!
          }
        });
      }
    }).start();
  }

  @Override public void onDestroyView() {
    mHandler.removeCallbacksAndMessages(null);
    super.onDestroyView();
  }
}

I notice at some point, in the onDestroyView, the handler has been remove all the pendding message or runnable which will attach to the ui thread, and the the view set to be null to be gc. But the thread may still in the running state, and the handler will post the runnable, but the view is null.

The simple way is to check null from fragment' s getView() in the runnable, but if all of this situation needs to check null, that would be tedious. Is there any nice approach to slove this kind of problem?

Thx in advance.

longkai
  • 3,598
  • 3
  • 22
  • 24

0 Answers0