Creating a Room database

Room is not a database but a layer of the SQLite database. It mainly uses DAO and the queries to make it easier to fetch the database for the clients. It doesn't use the main thread, but runs asynchronously on a background thread and so the UI performance doesn't fall.

Let's create an abstract class named UsersRoomDatabase and extend RoomDatabase. Use the @Database annotation with an entity of Users class and add the version number. Lastly, initialize an abstract function of the UserDao class:

@Database(entities = [Users::class], version = 1)
abstract class UsersRoomDatabase : RoomDatabase() {
abstract fun userDAO(): UserDAO
----
----
}

Let's create a singleton. This will handle multiple instances of the database when it opens at the same time.

Initialize the UsersRoomDatabase object.

The name of the UsersRoomDatabase is "user_database".

Here is the piece of code for this object:

// static members
companion object {
@Volatile
private var INSTANCE: UsersRoomDatabase? = null

fun getDatabase(context: Context, scope: CoroutineScope): UsersRoomDatabase {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
UsersRoomDatabase::class.java,
"user_database"
).addCallback(UserDatabaseCallback(scope))
.build()
INSTANCE = instance
return instance
}
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.85.221