I am working on an app in which i have two Fragments hosted in one Activity. The acitivity layout has a bottom bar which has buttons that switch the two fragments.
In those fragments there are Threads that do some internet work and then update their layout.
Hieararchy:
ActivityFragment1Thread1
Fragment2Thread2
The problem
The problem is that when, say Thread 1 starts doing some work, the user clicks the button to switch to Fragment 2, the Thread continues to run in the background, and when it is done with it's network task and tries to update the view (in the now not visible Fragment 1), the app crashes because getActivity() or getContext() now returns null.
EDIT: The thread uses getActivity() and getContext() a lot, not only for updating layout, but also for saving SharedPreferences, etc. I can add an inspection (if(!stopped) for example) to every line that uses Context, but i thought there is a better way than wrapping every step in an if condition.
So how do I kill either the Thread or Fragment completely? I don't need the background work running when the fragments are switched, I only need it to run when the fragment is visible.
I have tried both Thread.interrupt() and removing the fragment (instead of replacing) using getSupportFragmentManager.remove(Fragment fragment). Did not work.
Thanks in advance :)