re-Printing Chronometer value gives Integer value instead of String

82 views Asked by At

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()
}
2

There are 2 answers

0
Cyb3rKo On BEST ANSWER

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"
}
1
awh On
private  fun formattedChronometer(chronometer: Chronometer): String {
    val elapsedTime = SystemClock.elapsedRealtime() - chronometer.base
    val time = elapsedTime / 1000
    val minutes = time / 60
    val seconds = time % 60
    return String.format("%02d:%02d",minutes,seconds)
}

Managed to solve it using this function after looking into the documentation