androidkotlinchronometer

re-Printing Chronometer value gives Integer value instead of String


I am trying to pull a String value equal to the moment the chronometer stops as in "01:21" but the elapsed time gives an integer value, as in "11322".

val chronometer = findViewById<Chronometer>(R.id.chronometer)
chronometer.base = SystemClock.elapsedRealtime()
chronometer.format = "%s"
chronometer.start()
button.setOnClickListener {
    val elapsedTime = SystemClock.elapsedRealtime() - chronometer.base
    header.text = elapsedtime.toString()
    Toast.makeText(this,"$elapsedTime",Toast.LENGTH_SHORT).show()
}

Solution

  • To be precise you get a long value and not an integer because both SystemClock.elapsedRealtime() and chronometer.base return a long value.

    I have to disappoint you, currently there is no way to directly get the shown time of a chronometer, but of course you can convert the milliseconds you got to minutes and seconds, so you can show it again.


    Here's my example of how it could work:

    private fun calculateTime(chronometerMillis : Long) {
        val minutes = TimeUnit.MILLISECONDS.toMinutes(chronometerMillis)
        val seconds = TimeUnit.MILLISECONDS.toSeconds(chronometerMillis) - (minutes * 60)
    
        println("Recreated time: $minutes:$seconds")
    }
    

    If you now call this method with the value 81000, which is 1 Minute and 21 Seconds (just like your chronometer), it prints Recreated time: 1:21.


    To use it in your project just return a String:

    private fun calculateTime(chronometerMillis : Long) : String {
        val minutes = TimeUnit.MILLISECONDS.toMinutes(chronometerMillis)
        val seconds = TimeUnit.MILLISECONDS.toSeconds(chronometerMillis) - (minutes * 60)
    
        return "$minutes:$seconds"
    }