无法在我的测试应用程序中使用 Room 构建应用程序

Unable to build application with Room in my test App

当我尝试构建应用程序时出现错误

Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
   > java.lang.reflect.InvocationTargetException (no error message)

在build.gradle中我指定了

apply plugin: 'kotlin-kapt'

implementation "android.arch.persistence.room:runtime:1.1.1"
kapt 'android.arch.persistence.room:compiler:1.1.1'

我的数据库class

@Database(entities = [WeatherOfCities::class], version = 1, exportSchema = false)
public abstract class AppDatabase : RoomDatabase(){
    public abstract fun weatherOfCitiesDao(): WeatherOfCitiesDao
    companion object {
        private var INSTANCE: AppDatabase? = null
        fun getDatabase(context: Context): AppDatabase {
            if (INSTANCE == null) {
                synchronized(this) {
                    INSTANCE =
                        Room.databaseBuilder(context, AppDatabase::class.java, "database")
                            .build()
                }
            }
            return INSTANCE!!
        }
    }
}

我的实体class

@Entity
data class WeatherOfCities (
    @PrimaryKey(autoGenerate = true)
    val id: Long,
    val city: String,
    val weather: Int
)

My Dao 界面

@Dao
interface WeatherOfCitiesDao {
    @Query("SELECT * FROM weatherOfCities")
    fun getAll(): List<WeatherOfCities>
    @Insert
    fun insert(weatherOfCities: WeatherOfCities)
    @Update
    fun update(weatherOfCities: WeatherOfCities)
}

并在 MainActivity 中构建数据库

class MainActivity : AppCompatActivity(), MainView {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var presenter = (application as MVPApplication).mainPresenter
        presenter?.attachView(this)
        var db = AppDatabase.getDatabase(this)
        var weatherOfCitiesDao = db.weatherOfCitiesDao()
    }
}

为什么应用程序没有构建,是因为应用程序代码中的错误吗?

您需要添加 ktx 依赖项,例如

implementation 'androidx.room:room-ktx:1.1.1'

我还建议对所有房间相关性使用 2.4.1 而不是 1.1.1

所以使用2.4.1,.allowMainThreadQueries()(在.build()之前的AppDatabase

    //var presenter = (application as MVPApplication).mainPresenter
    //presenter?.attachView(this)
    var db = AppDatabase.getDatabase(this)
    var weatherOfCitiesDao = db.weatherOfCitiesDao()
    weatherOfCitiesDao.insert(WeatherOfCities(0,"London",10))
    weatherOfCitiesDao.insert(WeatherOfCities(0,"Paris",20))
    weatherOfCitiesDao.update(WeatherOfCities(2,"New York", 30))
    for(woc: WeatherOfCities in weatherOfCitiesDao.getAll()) {
        Log.d("DBINFO","ID =  ${woc.id} City is ${woc.city} Weather is ${woc.weather}")
    }

写入日志的结果是:-

D/DBINFO: ID =  1 City is London Weather is 10
D/DBINFO: ID =  2 City is New York Weather is 30

通过应用检查:-