How to save data in the local database using room?

What is Room Persistence Library?

Room Persistence Library provided by Google to implement a local database in Android

Room Persistence library provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite.

Room provides three major components

  1. Entity

Entity is nothing but a data class annotated with @Entity. An entity class represents a table in the database and its members represent columns of the table.

@Entity(tableName = "user_table")
data class User(
  @PrimaryKey
  val id: Int,
  val firstName: String?,
  val lastName: String?
 )

In this example, i have created a data class for the user above it I have annotated the data class with @Entity which tells room that it's a table inside it I have specified the table name.

  1. Dao

DAO stands for Data Access Objects. DAO is an interface annotated with @Dao that defines all the operations that we need to perform in our database. We can define methods that'll represent SQL queries to query the database.

We can easily insert, update, and delete by annotating the methods with @Insert, @Update, @delete respectively.

We can also annotate the method by @Query and write the SQL query between the parenthesis.

@Dao
interface UserDao {

  @Insert
  fun addUser(user: User)

 @Delete
 fun deleteUser(user: User)

 @Query("SELECT * FROM user")
 fun getAll(): List<User>
}

In this example, i have annotated UserDao interface ad Dao for the database inside it i have used an insert and delete annotation to add and delete the user also i wrote the function to return the list of users that is stored in the database.

  1. Database

This is an abstract class annotated with @Database, It contains the database holder and serves as the main access point to your app's data.

This class must extend RoomDatabase, include the entities associated with the database, contain an abstract method that returns the class annotated with @Dao

At runtime, you can acquire an instance of Database by calling Room.databaseBuilder()

@Database(entities = arrayOf(User::class), version = 1)
abstract class UserDatabase: RoomDatabase() {
    abstract fun userDao(): UserDao

    companion object {
            @Volatile
             private var INSTANCE: MovieDatabase? = null
             fun getDatabase(context: Context): MovieDatabase {
               return INSTANCE
             ?: synchronized(this) {
             val instance = Room.databaseBuilder(
             context.applicationContext,
             UserDatabase::class.java,
             "user_database"
         ).build()
         INSTANCE = instance
         instance
       }
    }
  }
}

To learn more about Room Persistence Library

Documentation: developer.android.com/training/data-storage..

Codelabs: developer.android.com/codelabs/kotlin-andro..