in my android application i\'m using Timer schedule.but getting Timer-0 fatal exception as below.how can i remove it.i have also mentioned code below -
01-28 13:
You can use a CountDownTimer
instead of the Timer
:
Timer timer = new CountDownTimer(Long.MAX_VALUE, 1000) {
public void onTick(long millisUntilFinished) {
// the code in the method run
}
public void onFinish() {
}
};
The methods onTick
and onFinish
will be called in the UI thread.
To make the timer start performing its action, run: timer.start()
It is very simple, you are scheduling the Timer but not cancelling it never. So Task scheduled will be in the queue and wait for its turn. By that time it should get executed your Activity might not be in the foreground and it is unable to find the views. So it is throwing the Fatal Exception. Inorder, to get rid of the above issue, you need to cancel the tasks whenever you are going from that particular activity by calling myTimer.cancel()
.
Or else
Use the Handler class.
use runOnUiThread for updating UI element from Timertask run Method as :
myTimer.schedule(new TimerTask() {
@Override
public void run() {
Current_Activity.this.runOnUiThread(new Runnable() {
public void run() {
// update UI here
}
});
}
},0, 1000);
runOnUiThread(new Runnable() {
public void run() {
//stuff that updates ui
}
});
try this
also look at
Android "Only the original thread that created a view hierarchy can touch its views."
CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch views
Only the original thread that created a view hierarchy can touch its views