Introduction to Room DB in Android

Most of the android apps we develop need where to store data offline,e.g a Todo App will need a "store" for the information you enter.That is what is called a database,while working on android you will mostly be using Room Database .

This is a beginner article explaining what Room is and its components.

What is Room?

Room is a persistence library which provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

What is a library?

This is a keyword you will come across almost daily when developing apps.Well, libraries are components which help us write less code. In this context,using SQLite meant you were supposed to write alot of lines of codes e.g 1000,with room you may only write 300 lines achieving the same stuff. Room being an abstraction layer also means it exists between the developer and SQLite.

Screenshot from 2021-09-21 00-15-46.png

It also has other advantages like;

  • Compile-time verification of SQL queries -> this means that incase you have errors it will notify you while building the app and not crashing when the users are using it.

  • Convenience annotations that minimize repetitive and error-prone boilerplate code.

  • Streamlined database migration paths.

Screenshot from 2021-09-21 00-39-35.png

Incase you are new to databases,they have a structure on how data is to be stored,what type of data and how to access the data.Just like the image above,as you can see we have the database,the columns and a function to insert an item .Room also follows the same structure and we'll go throught it.

Components of Room

1. Entity

  • Data stored is structured and means must be in tables.An entity represents a table within a database,this is where we where we define what type of data to be stored.
  • This class is annotated with @Entity, tableName is what will be used to identify our entity in the database.
@Entity(tableName = "users")
data class Person(
    @PrimaryKey val id: Int,
    @ColumnInfo("first_name") val firstName: String,
    val lastName: String
)
  • You use ColumnInfo when you want to use a different name in your database table different from the one you are using in your app variables.
  • A primary key is a unique identify and can't be the same to our users. For example,in the Government database our National Identity Card numbers are primary keys.These can also be generated automatically by adding
@PrimaryKey(autoGenerate = true) val id: Int

2.Dao

  • When working with with with databases you need to be able to perform certain operations like adding data or removing some data.Well DAO means data access objects and this is where you define the operations the you will want to perform in your database.
  • Just like any other database,in Room you can insert data,delete data,update existing data and fetch data to display to user.
  • This should be an interface and annotated with @Dao
@Dao
interface PersonDao {

    //select all users from users table
    @Query("SELECT * FROM users")
    fun getAllUsers(): List<Person>

    //insert a single record
    @Insert
    fun insertUser(person: Person)

    //delete a single record
    @Delete
    fun deleteUser(person: Person)

    //update a single record
    @Update
    fun updateUser(person: Person)
}

3.Database

  • This class holds the database.Should be an abstract class and extends RoomDatabase.
  • Should be annotated with @Database.
  • You should define all your entities(tables)-sometimes we have more then one entity.
  • Contains an abstract method returning the @Dao class.
@Database(entities = [Person::class],version = 1)
class UserDatabase: RoomDatabase() {
    abstract fun personDao:PersonDao

    //checks if the database exists and builds if it doesn't
    companion object {
        @Volatile
        private var  INSTANCE: UserDatabase? = null
        fun getDatabase(context: Context): UserDatabase? {
            when(INSTANCE){
                null -> INSTANCE = Room.databaseBuilder(
                    context,UserDatabase::class.java,
                    "user-db"
                ).build()
            }
            return INSTANCE
        }
    }
}

Thanks for reading,let's connect on twitter.