Wednesday, 12 June 2013

Timer Execption In Android

FATAL EXCEPTION: Timer-1 
"Only the original thread that created a view hierarchy can touch its views."

Above given exception occurred when I used following piece of code in my app.

public void onClick(View v) 
{
SetGlobal.parseQuestCount++;
SetGlobal.titleQuestCount++;
final Timer tmr = new Timer(); 
tmr.schedule(new TimerTask() {
 public void run() {  
setQuestion();
t.cancel(); 
}}, 1000);
}

This is because setQuestion() method (In my case) can only be called from UI thread, but it is called from  tmr.schedule(new TimerTask(){..}) method. So the following error occured.


To overcome the error use runOnUiThread(Runnable action) method. This Runs the specified action on the UI thread.
public void onClick(View v)
{
SetGlobal.parseQuestCount++;
SetGlobal.titleQuestCount++;

final Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
setQuestion();
tmr.cancel();
}
});
}}, 1000);
}


No comments:

Post a Comment