Type mismatch in dao insert - how to convert list of object to entity

Viewed 168

In my Kotlin application I'm using Retrofit to retrieve data from network and room to store these data locally.

In the ViewmMdel I want to get the asteroid objects and store them in local database. The main problem is the network call returns ArrayList of data class called Asteroid And the Dao expects an ArrayList of Asteroid Entity.

So basically I have 2 asteroids classes. One represents an entity for room and the other as model for network call.

I have this funcion in 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
        }
    }

}

Here getAsteroids in repository

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

insertFeed in Dao

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

Here's the error

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

You must convert com.asteroidradar.repository.db.entity.Asteroid com.asteroidradar.Asteroid by following code:

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

See the Kotlin documentation:

Related