Android timer updating a textview (UI) Android timer updating a textview (UI) android android

Android timer updating a textview (UI)


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.


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.


StopWatch.time.post(new Runnable() {    StopWatch.time.setText(formatIntoHHMMSS(elapsedTime));});

this code block is based on Handler but you don't need to create your own Handler instance.