I'm using fragments in my application. And the very common problem while using them are the NPE when using getActivity(). I know we can solve it by checking if getActivity() != null
every single time or checking if the fragment isAdded()
.
In one of my classes I'm getting activity's context in more than 60 places. Checking if getActivity()is not null or if the fragment is still added to the activity in all the places is making the code ugly,larger and non-maintainable. Is there any other way to handle this? Is it even possible to destroy the fragment(and stop any work it has been doing while being removed) when it is removed from the activity?