I know similar type of question is asked before. Sorry to ask again.
I have a fragment in a tab FragmentActivity. Within the fragment in onActivityCreated, I have to schedule a task after every fix interval.
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
new fetchDataInBackground(ctx).execute(); //async task
}
});
}
}, 0, 20000);
The above code works perfectly fine, until we press the back button over the tab activity.
Once back button is pressed it throws the null pointer exception on getActivity() of above code.
I guess may be fragment have been detached from the activity therefore getActivity() is returning null.
My question is how to achieve above scenario, so that the process should continue even if the back button is pressed. Any best practices?
I am returning the same instance of Fragment in getItem method from the FragmentPageAdapter.
Thanks in advance!