KC Blog

Mastering Android Persistent Storage: Kotlin and Room Database Practical Tutorial

4 min read
AndroidDev#Android#Kotlin

Introduction

  1. Import the required Room library according to your needs

  2. The main components of Room are as follows: Entity, DAO, Database

  3. To prevent UI blocking, Room does not allow database access on the main thread

Implementation

1. Create Entity

Using Room's @Entity annotation helps you create a table in the database

@PrimaryKey helps you create a unique primary key for each data entry

You can name table columns directly using variables, such as: id

You can also use @ColumnInfo(name = "name") to specify column names

2. Create DAO

Using Room's @Dao annotation helps you create methods to operate on the database

For example, @Insert: allows you to insert into the table

@Query: allows you to define custom SQL queries

Some commonly used SQL can be referenced from the official documentation

@Delete: deletes data

@Insert(onConflict = OnConflictStrategy.REPLACE): when there is a conflict with the primary key, it will replace instead of ignoring or doing nothing

@Update: updates data

3. Create Database

Use @Database to create a RoomDatabase

entities are the tables you want to create

version is used for version updates

4. Build Database

Use the code below to get an instance of RoomDatabase

5. Practical Operation of Room

Directly operate through the DAO written earlier

Other Usages

Asynchronous DAO Usage
Support Level
1. Room 2.1 supports suspend functions and uses Coroutines
  1. Room 2.2 supports Flow
  2. Others also support RxJava, LiveData, Guava, etc. For more information, see: Official Documentation
Using Coroutines to Operate Room
Using Flow and LiveData to Operate Room

After completing the above operations, you can use coroutines, flow, and LiveData as usual.

Pre-creating Database Content .db File
If you want to have preset data in the database, you can pre-embed the .db file containing the data into the storage path and then create it through createFromAsset

Or if you want to create it using a File, change it to .createFromFile(File("mypath"))

Type Converters
When the native supported variable types are not enough and you want to customize,

you can use @TypeConverters

to convert variable types and make them usable in Room.

For example, if you need to save a Date in the Room database, and Room doesn't know how to save Date objects, you can use:

Creating a TypeConverter
Adding to the DB
Now Usable in Room
Some Tips for Using Room Code
1. Support for Defining tableName with Labels and Multiple Primary Keys
2. Creating Embedded Objects and Data Classes to Store Fields
3. Defining Table Relationships
There are two tables

In some cases, you may want to retrieve corresponding data from both tables for use

Add corresponding parent and child entities, in this example, UserEntity and HistoryEntity.

Then add @Relation, where you need to input the corresponding unique key values, such as primaryKey.

In this example, parentColumn corresponds to the primaryKey of UserEntity

entityColumn corresponds to the primaryKey of HistoryEntity

Finally, add the operation method in the DAO:

Add @Transaction to ensure data consistency,

because sometimes when the database performs multiple operations,

such as operating on Table A and then on Table B,

if Table A is successfully retrieved but Table B fails,

the returned result might be incorrect.

So using @Transaction ensures that either all data is successfully retrieved or none at all,

preventing partial operations that result in inconsistent data.

4. Database Version Migration
- Automatic Update: In @Database, add the migration version: AutoMigration (from = 1, to = 2) will automatically migrate the database version. - Manual Update: Define the migration SQL commands through Migration room 1 Add Migration when building the Room db, for example: