I have an app that fetchs data from API using retrofit with coroutines. (Deferred)
I´m trying to implement a Room cache database for this, but I´ve just tried to use LiveData to fetch the data from Repository (not success). Tried to .alowMainThreadQueries (not success). The message is:
Attempt to invoke...... on a null object reference.
The main problem is: When i launch the App again, it fetches the data from the database and displays it correctly.
What am i doing wrong? This is my DAO
@Dao
interface VarietiesDao{
@Query("select * from pokevariationsentity where id = :id")
fun getVariety(id: Int): LiveData<PokeVariationsEntity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(pokes: PokeVariationsEntity) // will pass the pokes
}
private lateinit var INSTANCE : PokeVarietiesDatabase
fun getVarietiesDatabase(context: Context): PokeVarietiesDatabase {
synchronized(PokeVarietiesDatabase::class.java){
if(!::INSTANCE.isInitialized){
INSTANCE = Room.databaseBuilder(context.applicationContext,
PokeVarietiesDatabase::class.java,
"odaps2l.db").build() // name
}
}
return INSTANCE
}
Repo:
class VarietiesRepositoryImpl(private val database: PokeVarietiesDatabase, private val id: String) {
val varieties: LiveData<PokeVariety>
get() = Transformations.map(database.varietiesDao.getVariety(Integer.parseInt(id))){
it.asDomainModelFromVariations()
}
suspend fun refreshVarieties(id: String) {
withContext(Dispatchers.IO) {
val pokeList = PokeApi.retrofitService.getVariations(Integer.parseInt(id)).await()
database.varietiesDao.insertAll(pokeList.asDatabaseModel())
}
}
}
Actually i thought that the problem was the TypeConverter, but once it runs okay on the second time, that´s i realized that is nothing about it.
UPDATE
I just alowed .aloMainThreadQueries and tried to do it as Sync mode. returning an Object instead of LiveData. Surrounded the message Parameter specified as non-null is null: method
`kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter $this$asDomainModelFromVariations`
At the first time I click on the item, and the second time it Loads perfectly. The Same happens with livedata.