我正在尝试将我的应用程序从mutate
切换到Loader
和Room
s。我已经编写了自己的ViewModel
类:
App
我的视图模型:
class App : Application() {
lateinit var database: AppDatabase
private set
override fun onCreate() {
super.onCreate()
instance = this
database = Room.databaseBuilder(this, AppDatabase::class.java, AppDatabase.NAME)
.build()
}
companion object {
lateinit var instance : App
}
}
在open class BaseViewModel<TEntity, TDao: BaseDao<TEntity>, TRepo : Repository<TEntity, TDao>>(
app: App, protected val repository: TRepo) : AndroidViewModel(app) {
fun insert(entity: TEntity) {
repository.insert(entity)
}
fun update(entity: TEntity) {
repository.update(entity)
}
fun delete(entity: TEntity) {
repository.delete(entity)
}
}
class TimetableViewModel(app: App) : BaseViewModel<Timetable, TimetableDao, TimetableRepository>(
app, TimetableRepository(app.database)) {
internal val all: LiveData<List<Timetable>> = repository.getAll()
}
中,我的MainActivity.onCreate()
由下一行初始化:
TimetableViewModel
但是在启动时,应用程序崩溃并显示日志:
timetableVM = ViewModelProviders.of(this).get(TimetableViewModel::class.java)