Reputation: 30276
I have a fragment. In this fragment, I have a Timer that run a timertask periodically. I override onPause
so when switch fragment, TimerTask and timer will stop its work.
@Override
public void onPause() {
super.onPause();
timerTask.cancel();
timer.cancel();
timer.purge();
}
And Here is my code for switching fragment :
OrderFragment fragment2 = new OrderFragment();
fragment2.setArguments(arguments);
getSupportFragmentManager().beginTransaction().replace(R.id.item_detail_container, fragment2).commit();
But when I switch different fragment, I often receive Null Point Exception
because TimerTask cannot access UI Thread anymore (because I have used runOnUIThread
)
So, my question is : How to be sure that Timer and TimerTask stop all its work, before I can change fragment.
Thanks :)
Upvotes: 0
Views: 1020
Reputation: 10083
Put your timer
.cancle as a statement just above this as:
timer.cancel();
OrderFragment fragment2 = new OrderFragment();
fragment2.setArguments(arguments);
getSupportFragmentManager().beginTransaction().replace(R.id.item_detail_container,
fragment2).commit();
Declare private Timer timer; at class level
Upvotes: 0
Reputation: 2183
It seems like onHiddenChanged(boolean hidden) is what you need. From the Fragment
onPause()
documentation:
This is generally tied to Activity.onPause of the containing Activity's lifecycle.
So onPause()
isn't necessarily called when the Fragment is no longer visible. Move your timer canceling code into onHiddenChanged()
.
Upvotes: 1
Reputation: 12823
Your fragment may not go into the background simply by switching the displayed fragment. It's lifecycle is dependent on the Activity's. I think if you add Log.d("yourFragment", "onPause()");
to the onPause() method you'll find this to be true.
The fragment lifecycle can be found here:
http://developer.android.com/guide/components/fragments.html
Note that it says when your fragment is removed/replaced, but if you're merely displaying another fragment from your activity that doesn't count ;)
Upvotes: 1