Search code examples
javaandroidtimer

Using a timer to count seconds and update a string within the activity


I'm trying to make a timer within one of my activities that will get triggered every second, increment the seconds variable and then increasing minutes by one if seconds == 60, increasing hours by one if minutes == 60.

    _currentSeconds = _level.GetTimeSpentSeconds();
    _currentMinutes = _level.GetTimeSpentMinutes();
    _currentHours = _level.GetTimeSpentHours();

    String currentTimeDisplay = _currentHours + "H " + _currentMinutes +"M " + _currentSeconds +"S";

    _txtCurrentTime = findViewById(R.id.txtCurrentTime);
    _txtCurrentTime.setText(currentTimeDisplay);

    _totalGameTime = new Timer();
    _totalGameTime.schedule(new TimerTick(), 1000);

}

private class TimerTick extends TimerTask{
    TextView _txtCurrentTime = findViewById(R.id.txtCurrentTime);
    public void run()   {
        _currentSeconds++;
        TextView _txtCurrentTime = findViewById(R.id.txtCurrentTime);
        if (_currentSeconds == 60){
            _currentSeconds = 0;
            _currentMinutes++;
        }

        if (_currentMinutes == 60){
            _currentMinutes = 0;
            _currentHours++;
        }

        String currentTimeDisplay = _currentHours + "H " + _currentMinutes +"M " + _currentSeconds +"S";
        _txtCurrentTime.setText(currentTimeDisplay);
        _level.SetTimeSpentSeconds(_currentSeconds);
        _level.SetTimeSpentMinutes(_currentMinutes);
        _level.SetTimeSpentHours(_currentHours);
    }
}

It's hard to tell exactly how the program is responding because of how leggy my activity has gotten with the debugger attached but this doesn't seem to be doing the trick, the TextView stays the same.


Solution

  • For doing this, you need not use a TimerTask. You can use one of the following :

    1. You can use this class I have written for a similar purpose - CountUpTimer You will have to define onTick() to update your TextView every 'mCountUpInterval' time interval (defined in the CountUpInterval class)
    2. Chronometer