Use of Android Jetpack Room

Posted by bubblybabs on Mon, 03 Jan 2022 17:00:12 +0100

The official website link uses Room to save data to the local database | Android Developers | Android Developers
https://developer.android.google.cn/training/data-storage/room?hl=zh_cn

Room is used to process the database. It provides an abstraction layer on SQLite to make full use of the powerful functions of SQLite and smoothly access the database.

Google recommends using Room instead of SQLite.

Borrow the official website description,
The Room contains three main components:

  • Database: contains the database holder and serves as the main access point for the underlying connection of the application's retained persistent relational data.

    Classes annotated with @ Database should meet the following conditions:

    • Is an abstract class that extends RoomDatabase.
    • Add a list of entities associated with the database to the comment.
    • Contains an abstract method that has 0 parameters and returns a class annotated with @ Dao.
    • At runtime, you can call room Databasebuilder () or room Inmemorydatabase builder() gets an instance of Database.
  • Entity: represents a table in the database.

  • DAO: contains methods for accessing the database.

Start using.

1. Add dependency

In the app's build Add dependencies to gradle,

dependencies {
    def room_version = "2.3.0"

    // Room
    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version" //An error will be reported if not added
}

Add plug-in kotlin kapt

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
    id 'kotlin-kapt' //This line
}

2. Realize Entity

Entity identifies the table in the database, which is actually the corresponding JavaBean.

import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity
data class Customer(var name:String ,var profession:String, var deposit: Long) {

    @PrimaryKey(autoGenerate = true)
    var id:Long = 0

}

Here, the Customer class is created and declared as an Entity class with the @ Entity annotation.

Add the id field in the class and set it as the primary key with the @ PrimaryKey annotation. autoGenerate = true makes the primary key automatically generated.

3. Define Dao interface

Dao is the method to access the database. It is generally to add, delete, modify and query, but it should cover all business requirements.

import androidx.room.*

@Dao
interface MyCustomerDao {

    @Insert
    fun insertCustomer(customer: Customer):Long

    @Update
    fun updateCustomer(newCustomer: Customer)

    @Query("select * from Customer")
    fun getAllCustomer(): List<Customer>

    @Query("select * from Customer where name = :name")
    fun queryCustomerByName(name: String): List<Customer>

    @Query("select * from Customer where deposit >= :deposit")
    fun queryCustomerByDeposit(deposit: Long): List<Customer>

    @Delete
    fun deleteCustomer(customer: Customer)

    @Query("delete from Customer where name = :name")
    fun deleteCustomerByName(name: String)
}

Declare an interface and use @ Dao annotation so that Room knows it is Dao.

The addition, deletion and modification methods are annotated with @ Insert, @ Delete, @ Update and @ Query respectively.

Some SQL statements are required. Room supports compile time checking. If there is an error in the SQL statement, an error will be reported during compilation, which can be found in time.

4. Implement custom RoomDatabase

Write abstract classes, inherit RoomDatabase,

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

@Database(version = 1, entities = [Customer::class])
abstract class MyDatabase: RoomDatabase(){

    abstract fun myCustomerDao() : MyCustomerDao

    companion object {
        private var instant: MyDatabase ?= null

        @Synchronized
        fun getDatabase(context: Context): MyDatabase {
            instant?.let { return it }

            return Room.databaseBuilder(
                context.applicationContext,
                MyDatabase::class.java,
                "my_database"
            )
            	.allowMainThreadQueries()
                .build()
                .apply {
                    instant = this
                }
        }
    }
}

It is declared as an abstract class MyDatabase. The header of the class uses the @ Database annotation, and the version number and the contained Entity class (that is, Entity) are declared in the annotation.

Class to get the instance of Dao.
Write a singleton in the company object {} using room The databasebuilder () method creates a MyDatabase instance and passes in three parameters. The first parameter is context, the second parameter is the class type of MyDatabase, and the third parameter is the database name.

Database operations are time-consuming. By default, Room does not allow operations in the main thread, so these operations should be placed in the child thread.
To facilitate debugging, you can use the allowMainThreadQueries() method when creating a database instance to operate on the main thread. This method is recommended for debugging. After all, it is not good for the main thread to perform time-consuming operations.

5. Use

Get Dao instance,

val dao = MyDatabase.getDatabase(this).myCustomerDao()

Call the defined Dao interface to add, delete, modify and query,

Add (i.e. insert data)

var customer1 = Customer("Zhang", "Student", 100)
var customer2 = Customer("Li", "Student", 200)
var customer3 = Customer("Wang", "Student", 300)

customer1.id = dao.insertCustomer(customer1)
customer2.id = dao.insertCustomer(customer2)
customer3.id = dao.insertCustomer(customer3)

Delete

dao.deleteCustomerByName("Wang")
dao.deleteCustomer(customer3)

Change (i.e. update)

customer3.deposit = 500
dao.updateCustomer(customer3)

check

val list = dao.getAllCustomer()
val list = dao.queryCustomerByDeposit(200)

Topics: Android kotlin jetpack room