I’m trying to create a stop watch application. Everything works fine at first. The stop watch goes up from the milliseconds, to the seconds, to the minutes just fine. There are two timers, one of the current time and one for the lap time. The problem comes when trying to add laps.
The laps are saved into Room so they’ll stay there on recomposition. The current time and the lap time are retrieved and placed into an item into a lazy column. However, the first lap is empty and the time is around four seconds to early. For example, if you created a lap at seven seconds it would actually say three seconds.
Here is the Main Activity. There is an instance of the viewmodel and database at the top. There are two sets of three variables representing the time. One set is for the current time, one set is for the lap time. The timers are triggered by booleans that start a launched effect. There is a button to start/stop, reset, and lap the timer. Underneath that is a lazy column that displays the laps.
class MainActivity : ComponentActivity() {
private val stopWatchDatabase by lazy {
Room.databaseBuilder(
applicationContext,
StopWatchDatabase::class.java,
name = "object.database"
).build()
}
private val viewModel by viewModels<StopWatchViewModel> (
factoryProducer = {
object: ViewModelProvider.Factory{
override fun <T: ViewModel> create(modelClass: Class<T>): T{
return StopWatchViewModel((stopWatchDatabase)) as T
}
}
}
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
// Time
var milliseconds by remember { mutableIntStateOf(0) }
var seconds by remember { mutableIntStateOf(0) }
var minutes by remember { mutableIntStateOf(0) }
// Lap Time
var lapMilliseconds by remember { mutableIntStateOf(0) }
var lapSeconds by remember { mutableIntStateOf(0) }
var lapMinutes by remember { mutableIntStateOf(0) }
// Time Display
var overallTime by remember { mutableStateOf("") }
var lapTime by remember { mutableStateOf("") }
// Timer Active States
var isTimerActive by remember { mutableStateOf(false) }
var isLapTimerActive by remember { mutableStateOf(false) }
// Lap List
var laps by remember { mutableStateOf(listOf<Lap>()) }
// Instance Of Lap Entity
val newLap = Lap(
lapNumber = laps.size + 1,
overallTime = overallTime,
lapTime = lapTime
)
// Function To Retrieve Lap List
viewModel.retrieveAllLaps().observe(LocalLifecycleOwner.current) {
laps = it
}
// Start Timer Launched Effect
LaunchedEffect(isTimerActive) {
while (isTimerActive && milliseconds < 100) {
delay(1)
milliseconds++
while (milliseconds == 100) {
seconds += 1
milliseconds = 0
while (seconds == 60) {
minutes += 1
seconds = 0
milliseconds = 0
}
}
}
}
// Start Lap Timer Launched Effect
LaunchedEffect(isTimerActive && isLapTimerActive) {
while (isTimerActive && isLapTimerActive && lapMilliseconds < 100) {
delay(1)
lapMilliseconds++
while (lapMilliseconds == 100) {
lapSeconds += 1
lapMilliseconds = 0
while (lapSeconds == 60) {
lapMinutes += 1
lapSeconds = 0
lapMilliseconds = 0
}
}
}
}
// App Layout
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.fillMaxSize()
) {
// Time Display
Text(
text = "%02d:%02d:%02d".format(minutes, seconds, milliseconds),
fontSize = 50.sp
)
if (isLapTimerActive) {
// Lap Time Display
Text(
text = "%02d:%02d:%02d".format(lapMinutes, lapSeconds, lapMilliseconds),)
}
// Button To Start Timer
Button(onClick = { isTimerActive = !isTimerActive }) {
Text(text = "Start")
}
// Button To Reset Timer
Button(onClick = {
CoroutineScope(Dispatchers.IO).launch {
isTimerActive = false
isLapTimerActive = false
viewModel.deleteAllLaps()
delay(1)
milliseconds = 0
seconds = 0
minutes = 0
lapMilliseconds = 0
lapSeconds = 0
lapMinutes = 0
overallTime = ""
lapTime = ""
}}) {
Text(text = "Reset")
}
// Button To Lap Timer
Button(onClick = {
overallTime = "%02d:%02d:%02d".format(minutes, seconds, milliseconds)
lapTime = "%02d:%02d:%02d".format(lapMinutes, lapSeconds, lapMilliseconds)
viewModel.insertLap(newLap)
lapMilliseconds = 0
lapSeconds = 0
lapMinutes = 0
isLapTimerActive = true
}) {
Text(text = "Lap")
}
// Lap List
LazyColumn(
verticalArrangement = Arrangement.spacedBy(30.dp)
) {
items(laps) { lap ->
Row(
horizontalArrangement = Arrangement.spacedBy(30.dp)
) {
Text(text = lap.lapNumber.toString())
Text(text = lap.lapTime)
Text(text = lap.overallTime)
}
}
}
}
}
}
}
Here is Lap Entity
@Entity
data class Lap(
val lapNumber: Int?,
val overallTime: String,
var lapTime: String,
@PrimaryKey(autoGenerate = true)
val id: Int = 0
)
Here is the Stopwatch Dao
@Dao
interface StopWatchDao {
@Upsert
suspend fun insertLap(lap: Lap)
@Query("DELETE FROM Lap")
suspend fun deleteAllLaps()
@Query("SELECT * FROM Lap")
fun retrieveAllLaps(): Flow<List<Lap>>
}
Here is the Stopwatch Database
@Database(
entities = [Lap::class],
version = 1
)
abstract class StopWatchDatabase: RoomDatabase() {
abstract val stopWatchDao: StopWatchDao
}
And finally the Stopwatch ViewModel
class StopWatchViewModel(private val stopWatchDatabase: StopWatchDatabase): ViewModel() {
fun insertLap(lap: Lap){
viewModelScope.launch {
stopWatchDatabase.stopWatchDao.insertLap(lap)
}
}
fun deleteAllLaps(){
viewModelScope.launch {
stopWatchDatabase.stopWatchDao.deleteAllLaps()
}
}
fun retrieveAllLaps() = stopWatchDatabase.stopWatchDao.retrieveAllLaps().asLiveData(viewModelScope.coroutineContext)
}
I tried placing the insertLap function into coroutine and adding a delay but that didn’t work.
But away the problem is that the first lap in the lazy column is empty except for the lap number and the time on the rest is four seconds too early.
Thanks for your time reading my question.