-3

I am getting a null pointer exception in the line given in code below. The problem is, the exception occurs randomly. Many times it just works but sometimes it throws an exception (say 5% of times). Any help would be appreciated.

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
        Animation animation = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.dialog_main_show_amination);  //Exception in this line
        fabAddDeliveryBoy.startAnimation(animation);
        fabAddDeliveryBoy.setVisibility(View.VISIBLE);
     }
}, 500);
Hacketo
  • 4,978
  • 4
  • 19
  • 34
VipulKumar
  • 2,385
  • 1
  • 22
  • 28

1 Answers1

3

The problem is that your handler is not tied to your fragment lifecycle. The handler messages can fire even after the fragment is detached from its activity, and getActivity() will return null.

As a quick fix, you can put your Runnable in a variable and clear the handler in e.g. onDestroyView():

handler.removeCallbacks(runnable);

For a more elegant solution, consider making the delay a part of the animation itself.

laalto
  • 150,114
  • 66
  • 286
  • 303
  • Thank you so much. It looks like a valid solution but I can't exactly tell because there is no way to test. It just happens randomly. I have accepted the answer and I will ask again here if the problem persists. – VipulKumar Dec 16 '14 at 09:14