nakashimaakioのブログ

Androidアプリエンジニア / 記事に「はてなスター」よろしくお願いします。

【Android Studio】【Room】アプリ内データ保存処理

はじめに

Roomを使用したアプリ内データ保存処理について解説。

手順

1. ライブラリ導入

dependencies {
    //...(略)

    //ksp利用のためのライブラリ
    implementation(libs.symbol.processing.api)

    //Roomライブラリ
    implementation(libs.androidx.room.runtime)
    implementation(libs.androidx.room.ktx)
    ksp(libs.androidx.room.compiler)
}

2. Entityデータクラス作成

データを格納するクラスを作成。

@Entity(tableName = "person")
data class PersonEntity(
    @PrimaryKey
    @ColumnInfo(name = "id")
    val id: Int,
    @ColumnInfo(name = "name")
    val name: String
)

3. Daoインターフェースクラス作成

データの読み込み・書き込みを行うメソッドを作成。Daoとは「Data Access Object」のこと。

@Dao
interface PersonDao {
    @Query("SELECT * FROM person")
    fun loadPerson(): List<PersonEntity>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun savePerson(personEntity: PersonEntity)
}

4. データベースクラス作成

Daoクラスを使用するためのメソッド作成。

@Database(entities = [PersonEntity::class], version = 1)
abstract class Database : RoomDatabase() {
    abstract fun personDao(): PersonDao
}

5. 作成したデータベースを使用

実際にデータベースの読み込み・書き込みを行う。

//データベース使用準備
val database = Room.databaseBuilder(applicationContext, Database::class.java, "database").build()
val personDao = database.personDao()

CoroutineScope(Dispatchers.IO).launch {
    // 読み込み
    val person = personDao.loadPerson()
}

//ボタン押下するとPersonデータクラスを生成して書き込む
binding.button.setOnClickListener {
    //ランダムにPersonデータクラスを生成
    val item = PersonEntity(
        (0..10000).random(),
        listOf("佐藤", "鈴木", "伊藤", "前田", "斉藤", "佐々木", "山本", "山田", "田中").random()
    )

    CoroutineScope(Dispatchers.IO).launch {
        //書き込み
        personDao.savePerson(item)
    }
}