Android timer updating a textview (UI)

I'm using a timer to create a stop watch. The timer works by increasing a integer value. I want to then display this value in the activity by constantly updating a textview.

Here's my code from the service where I try and update the activity's textview:

protected static void startTimer() {
    isTimerRunning = true; 
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            elapsedTime += 1; //increase every sec
            StopWatch.time.setText(formatIntoHHMMSS(elapsedTime)); //this is the textview
        }
    }, 0, 1000);
}

I got some kind of error about updating the UI in the wrong thread.

How can I adapt my code to accomplish this task of constantly updating the textview?


Solution 1:

protected static void startTimer() {
    isTimerRunning = true; 
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            elapsedTime += 1; //increase every sec
            mHandler.obtainMessage(1).sendToTarget();
        }
    }, 0, 1000);
}

public Handler mHandler = new Handler() {
    public void handleMessage(Message msg) {
        StopWatch.time.setText(formatIntoHHMMSS(elapsedTime)); //this is the textview
    }
};

Above code will work...

Note: Handlers must be created in your main thread so that you can modify UI content.

Solution 2:

You should use Handler instead to update UI every X seconds. Here is another question that show an example: Repeat a task with a time delay?

Your approach doesn't work because you are trying to update UI from non-UI thread. This is not allowed.