在 Kotlin 從1.5.10 升級到 1.5.20 時發現,Room不能導出 schemas 了,並且出現如下報錯:
Schema export directory is not provided to the annotation processor so we cannot export the schema.
You can either provide `room.schemaLocation` annotation processor argument OR set exportSchema to false.
public abstract class MyDatabase extends androidx.room.RoomDatabase {
這裏提示的很清楚了,說是沒有設置 schema 的導出目錄。
可以設置 room.schemaLocation
註解處理器參數,也可以將 exportSchema 設置爲 false。
不過項目中,一直是按照 Google文檔 中的要求配置了 room.schemaLocation
:
我的項目代碼:
android {
compileSdkVersion 30
defaultConfig {
applicationId "xxx"
minSdkVersion 23
targetSdkVersion 30
versionCode 1
versionName "1.0"
javaCompileOptions {
annotationProcessorOptions {
arguments = [
"room.schemaLocation": "$projectDir/schemas".toString()
]
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
經過測試,將 Kotlin 版本降爲 1.5.10,schemas 可以正常導出,由此我猜測,應該是在 Kotlin 版本升級中,註解處理器的語法有了變動。
果不其然,在 Kotlin 的文檔 中看到:使用 arguments {}
將參數傳遞給註解處理器:
kapt {
arguments {
arg("key", "value")
}
}
按照上面的格式重寫修改:
android {
...
kapt {
arguments {
arg("room.schemaLocation", "$projectDir/schemas".toString())
}
}
}
...
}
再次build,成功導出 schemas 文件。
最後再吐槽下 Google 文檔更新的太不及時了,畢竟 Kotlin 1.5.20 正式版出來這麼久了。