Creating A Room Database For A SleepNight Rating Android App Using Kotlin

in GEMS4 years ago

Hey, everyone, it's been a long time since I posted here. My non-posting attitude doesn't mean I haven't been active. In fact, I have been reading updates, being supportive of the community right from when we were all fighting over the hijacking of our first love blockchain(Steem). That said, I am glad that I'm back to Hive to keep in touch with my old folks and the new adopters of the hive blockchain.


In this post, I am not really gonna dive deep discussing what I have been up to since I left posting on the blockchain, but to keep the community updated with the current challenge I have accepted for myself, and here it is;


I have been learning Android development with Kotlin for a while now and have promised myself to keep my profile updated with my programming journey. I hope I'd be adding value to the Hive blockchain.


Here's the last topic I treated;


Creating A Room Database For A SleepNight Rating Android App


This section of the program I'm running really took me a lot of time to grab. Not because it's difficult but because I was so not inspired to learn it. But here I am today about to post what I have done so far in less than 3hrs.

The mobile application I'm working on has the functionality for users to start it before they sleep, stop the app after they wake, and then request for the rating of the sleep for that particular night.

To successfully create a database for the app, three Kotlin files are needed;

  • An Entity class
  • A Dao(Data access object) interface
  • An abstract Database class

Creating An Entity Class

The mobile application I am working on requires a database that will hold four different Entities;

  • Night I.D
  • Start time
  • End time
  • Sleep Rating

From the document I'm learning with, here's what it says about the Entity class;

  • An entity represents an object or concept, and its properties, to store in the database. An entity class defines a table, and each instance of that class represents a row in the table. Each property defines a column. In your app, the entity is going to hold information about a night of sleep.
  • A query is a request for data or information from a database table or combination of tables, or a request to perform an action on the data. Common queries are for; getting, inserting, and updating entities. For example, you could query for all the sleep nights on record, sorted by start time.

Below is my Entity class. I annotated it with @Entity then Specified a name for the table in the database. The primary key is set to auto-generate itself as new columns are entered into the table. The startTime and endTime will be in system time format while the sleep Quality rating is set to -1 which indicates that no data has been collected.

carbon (1).png

import android.nfc.tech.NfcA
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "daily_sleep_quality_table")
data class SleepNight(
        @PrimaryKey(autoGenerate = true)
        var nightId: Long = 0L,
        @ColumnInfo(name = "start_time_milli")
        var startTime: Long = System.currentTimeMillis(),
        @ColumnInfo(name = "end_time_milli")
        var endTime: Long = startTime,
        @ColumnInfo(name = "quality_rating")
        var sleepQuality: Int = -1

)

Creating A Dao Interface

This is an interface that will have access to both the database and the Entity class. As you can see, functions like; Insert(), Update() are written here. Also, quarries to access the Database are here. Below are the queries in this Dao.

  • Select all the entries in the table
  • Delete and supply all the entries in the table
  • Select and sort the entries in descending order by limit 1 to getTonight()
  • Select and sort the entries in descending order to get allNights

carbon (2).png

import androidx.lifecycle.LiveData
import androidx.room.*

@Dao
interface SleepDatabaseDao{
    @Insert
    fun insert(night: SleepNight)
    @Update
    fun update(night: SleepNight)

    @Query("SELECT * from daily_sleep_quality_table  WHERE nightId = :key")
    fun get(key: Long): SleepNight?
    @Query("DELETE from daily_sleep_quality_table")
    fun clear()
    @Query("SELECT * FROM daily_sleep_quality_table ORDER BY nightId DESC LIMIT 1")
    fun getTonight(): SleepNight?
    @Query("SELECT * FROM daily_sleep_quality_table ORDER BY nightId DESC")
    fun getAllNight(): LiveData<List<SleepNight>>

}

Creating The Database

The code in this section is more like a template for creating SQLite databases for Android apps. This means it's reusable. All you have to do is locate where I called my database table, delete it, and replace it with yours.

carbon (3).png

import android.content.Context
import androidx.room.Database
import androidx.room.Entity
import androidx.room.Room
import androidx.room.RoomDatabase

@Database(entities = [SleepNight::class], version = 1, exportSchema = false)
abstract class SleepDatabase : RoomDatabase() {

    abstract val sleepDatabaseDao: SleepDatabaseDao

    companion object {

        @Volatile
        private var INSTANCE: SleepDatabase? = null

        fun getInstance(context: Context): SleepDatabase {
            synchronized(this) {
                var instance = INSTANCE

                if (instance == null) {
                    instance = Room.databaseBuilder(
                            context.applicationContext,
                            SleepDatabase::class.java,
                            "sleep_history_database"
                    )
                            .fallbackToDestructiveMigration()
                            .build()
                    INSTANCE = instance
                }
                return instance
            }
        }
    }
}

My next challenge is to learn how to;

  • How threads work in Android.
  • How to use Kotlin coroutines to move database operations away from the main thread.
  • How to display formatted data in a TextView.

I promise to keep my Hive updated.