问题描述
在我的 Kotlin 应用程序中,我使用 Retrofit 从网络和空间中检索数据以在本地存储这些数据。
在 ViewmMdel
中,我想获取 asteroid
对象并将它们存储在本地数据库中。
主要问题是网络调用返回名为 Asteroid 的数据类的 ArrayList
而 Dao
期望 ArrayList
为 Asteroid
实体。
所以基本上我有 2 个小行星类。一个代表房间的实体,另一个代表网络调用的模型。
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())