dao insert 中的类型不匹配 - 如何将对象列表转换为实体

问题描述

在我的 Kotlin 应用程序中,我使用 Retrofit 从网络和空间中检索数据以在本地存储这些数据。

ViewmMdel 中,我想获取 asteroid 对象并将它们存储在本地数据库中。 主要问题是网络调用返回名为 Asteroid 的数据类的 ArrayListDao 期望 ArrayListAsteroid 实体。

所以基本上我有 2 个小行星类。一个代表房间的实体,另一个代表网络调用的模型。

我在 viewmodel 中有这个功能

private fun getAsteroids() {
    viewmodelScope.launch {
        try {
            var result = repository.getAsteroid()
            _asteroidList.value = result.toMutableList()
            appLocalDb.asteroidDao.insertFeed(result)
           
        } catch (e : Exception) {
            _asteroidList.value = null
        }
    }

}

这里是存储库中的 getAsteroids

   override suspend fun getAsteroid(): ArrayList<Asteroid> {
        return apiRepositoryImp.getAsteroids();
    }

insertFeed 在道中

@Dao
interface AsteroidDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertFeed(vararg asteroid: Asteroid)
}

这里是错误

required:
com.asteroidradar.repository.db.entity.Asteroid
Found:
kotlin.collections.ArrayList<com.asteroidradar.Asteroid> /* = java.util.ArrayList<com.asteroidradar.Asteroid> */

解决方法

您必须通过以下代码转换 com.asteroidradar.repository.db.entity.Asteroid com.asteroidradar.Asteroid

 var result = repository.getAsteroid()
 _asteroidList.value = result.toMutableList()
 appLocalDb.asteroidDao.insertFeed(*result.map{ repoAsteroid ->
    com.asteroidradar.Asteroid(
      //Set full properties here
    )
 }.toTypedArray())

Kotlin documentation

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...