一覧画面用のテーブルを追加します。
List01Dataテーブルを作成します。
エンティティ(テーブル)定義クラスを作成します。
List01Data.ktを作成します。
package jp.co.example.android01.core.data import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "list01_data") data class List01Data( @PrimaryKey val key: String = "", val col1: String = "", val col2: String = "", val col3: 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> }
データベース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, `col1` TEXT NOT NULL, `col2` TEXT NOT NULL, `col3` 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() } :