//MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.content_main)
val database = getDatabase(this)
val repository = TaskRepository( database.purposeDao)
// Get the ViewModel.
model = ViewModelProviders
.of(this, TaskViewModel.FACTORY(repository))
.get(TaskViewModel::class.java)
//中略
}
//AppDatabase.kt
@Database(entities = [Purpose::class], version = 2)
abstract class AppDatabase : RoomDatabase() {
//abstract fun purposeDao(): PurposeDao
abstract val purposeDao: PurposeDao
}
private lateinit var INSTANCE: AppDatabase
fun getDatabase(context: Context): AppDatabase {
synchronized(AppDatabase::class) {
if (!::INSTANCE.isInitialized) {
INSTANCE = Room
.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"task-admin"
)
.fallbackToDestructiveMigration()
.build()
}
}
return INSTANCE
}