1.lifecycle的DefaultLifecycleObserver
添加依赖:implementation("androidx.lifecycle:lifecycle-common-java8:2.4.1")
2.viewModle的viewModles
添加依赖:implementation "androidx.activity:activity-ktx:1.4.0"
implementation "androidx.fragment:fragment-ktx:1.3.0"
3.room
*1*报错 java.lang.RuntimeException: cannot find implementation for com.app.room.AppDatabase. AppDatabase_Impl does not exist
第一步
![](https://img-blog.csdnimg.cn/693cf93a88154865ac181c6013d3f85a.png)
第二步
![](https://img-blog.csdnimg.cn/95f15aac7f0a4837b1009d64173153fd.png)
*2*报错 java.lang.IllegalStateException: Cannot access database on the
main thread since it may potentially lock the UI for a long period of time.
--必须在子线程请求数据库
*3*报错 java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the
version number. You can simply fix this by increasing the version number.
--如果数据库有任何更改 都需要版本升级
*4* 数据库升级---
Room 在 2.4.0-alpha01 及更高版本中支持自动迁移
自动升级
A.在app下的build.gradle中添加
android {
...
defaultConfig {
...
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
}
}
B.如果user里面修改任何字段,在database中的注解需要--version增加,autoMigrations = [ AutoMigration(from = 1, to = 2) ]
![](https://img-blog.csdnimg.cn/aa720691f1684af1b6b74f409bf8f480.png)
C.如果新增加一个student
![](https://img-blog.csdnimg.cn/775aedc71f0546c3bc2e5bc230701a81.png)