1

Question is not about solving that null return, it is about best practices to prevent from occurring.

  • What mistakes should one avoid while working with fragments to avoid getting null on getActivity() method? Especially fragments on viewpagers.
  • Usually when this happens and under what circumstances?
Nishant Shah
  • 2,022
  • 22
  • 20
  • 1
    refer https://stackoverflow.com/questions/11631408/android-fragment-getactivity-sometimes-returns-null – sasikumar Dec 04 '17 at 11:11
  • [calling-activity-method-from-inside-a-fragment](https://stackoverflow.com/a/19726742/8171292) Check this out,This might help you. – saurabh yadav Dec 04 '17 at 11:21

1 Answers1

0

If you are running code that gets null for getActivity() or getContext() for that matter, that means that your code is running after your fragment has been detached, onDetach() was called.

This happens probably because you were running an async operation, and when the result came back your fragment was detached from the activity, or it might even have been destroyed. So in this case it is valid to find getActivity to return null, and in this case you just need to either:

  • Do nothing, because you wanted to update the fragment's view, but that's not shown to the user anymore.
  • Save the data you or the state you got so you can re-use it when/if the fragment is re-attached again.
elmorabea
  • 3,243
  • 1
  • 14
  • 20