The next task I gave myself after my last blog post was to learn the followings;
- How to update an existing sleep-quality record in the database.
- How to use LiveData to track button states.
- How to display a snackbar in response to an event.
A day after I published that blog, I then realized that I didn't explain or complete the functionality of the remaining buttons on the SleepTrackerApp.
In my previous post, we wrote a function for the Start button code and we are left with Stop button and clear button code. This is exactly the two things we will be doing in this post. In other words, we aren't gonna waste any time.
Creating A Function For The Button To Stop The TackerApp
Just as we did while creating our onStartSleepTracking() function, we will do the same here.
fun onStopSleepTracking() {
uiScope.launch {
val oldNight = toNight.value?: return@launch
oldNight.endTime = System.currentTimeMillis()
update(oldNight)
}
}
As you can see from the code above, we launched a coroutine inside the uiScope that we defined in my previous post. Also, we declared a val variable which is oldnight to be equal to the system current time if it doesn't have a value yet. And then, we called the Update() function which we will be creating next to update the oldNight.
Let's create the update() funtion
private suspend fun update(night: SleepNight) {
withContext(Dispatchers.IO) {
database.update(night)
}
}
Updating The XML File For Stop Button
Just as we did in my previous post, the Xml file is ready for dataBinding. so, paste this code to handle the stop button.
android:onClick="@{() -> sleepTrackerViewModel.onStopTracking()}"
Now, let's build and run the project

Creating A Function For The Button To Clear The Data On The TrackerAPP
Just as we did earlier, let's create a suspended clear() function with a context to access the database ( Dispatchers.IO) to clear the saved data.
Create an onClear() function for the clear button. In the onClear function, the value for toNight is set as null. The clear() is called inside the onClear() function before setting the value for toNight is set as null.
fun onClear() {
uiScope.launch {
clear()
tonight.value = null
}
}
suspend fun clear() {
withContext(Dispatchers.IO) {
database.clear()
}
}
Let's update the clear button in the Xml file
android:onClick="@{() -> sleepTrackerViewModel.onClear()}"
That's all for this blog, I will be learning the following next;
- How to update an existing sleep-quality record in the database.
- How to use LiveData to track button states.
- How to display a snackbar in response to an event.
Thanks for telling the remaining button function in the sleep tracker app. It will help other developer how to share DIY work. We are looking for people like you in our community
Your post has been curated with @gitplait community account because this is the kind of publications we like to see in our community.
Join our Community on Hive and Chat with us on Discord.