一覧画面用のテーブルを追加します。
List01Dataテーブルを作成します。
エンティティ(テーブル)定義クラスを作成します。
List01Data.ktを作成します。
package jp.co.example.android01.core.data import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.ColumnInfo @Entity(tableName = "list01_data") data class List01Data( @PrimaryKey val key: String = "", @ColumnInfo(name = "occ_date") val occDate: String = "", // 発生日 YYYY-MM-DD val data1: String = "", val data2: String = "", val data3: String = "" )
データベースにアクセスするためのインターフェースオブジェクト(DAO)を作成します。
package jp.co.example.android01.core.data
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Insert
import androidx.room.OnConflictStrategy
@Dao
interface List01DataDao {
@Query("SELECT * FROM list01_data")
suspend fun getAllListData(): List<List01Data>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertListDataByList(listDataList: List<List01Data>): List<Long>
@Query("DELETE FROM list01_data WHERE occ_date < :topDate")
suspend fun deletePastData(topDate: String): Int
}
データベースAppDatabaseクラスに作成したエンティティ(テーブル)を追加します。
:
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
:
@Database(
entities = [SiteUrl::class],
entities = [SiteUrl::class, List01Data::class],
version = 1,
version = 2,
exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
abstract fun siteUrlDao(): SiteUrlDao
abstract fun list01DataDao(): List01DataDao
companion object {
:
/**
* バージョン1から2へのマイグレーション
* List01Dataテーブルを追加
*/
private val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
// List01Dataテーブルを作成
database.execSQL("""
CREATE TABLE IF NOT EXISTS `list01_data` (
`key` TEXT NOT NULL,
`occ_date` TEXT NOT NULL,
`data1` TEXT NOT NULL,
`data2` TEXT NOT NULL,
`data3` TEXT NOT NULL,
PRIMARY KEY(`key`)
)
""".trimIndent())
}
}
fun getDatabase(context: Context): AppDatabase {
:
.addMigrations(MIGRATION_1_2)
.build()
:
List01DataDaoをDI(Hilt)モジュールに追加して、Hiltに生成(注入)方法を伝えます。
:
import jp.co.example.android01.core.data.List01DataDao
:
object HiltModule {
:
@Provides
fun provideList01DataDao(database: AppDatabase): List01DataDao {
return database.list01DataDao()
}
: