0

My app has the following sequence. In the Database layer i have the query that returns LiveData

@Query("Select * from sites where server_id = :serverId and site_id = :siteId")
fun getSite(serverId: Long, siteId: Int): LiveData<SiteDto>

In my repository i have a function that returns that query

override fun retrieveSite(serverId: Long, siteId: Int): LiveData<SiteDto> {
        return sitesDao.getSite(serverId, siteId)
    }

And in my Activity i observe the SiteDto so i can display some information about it BUT only under some condition that comes from the Intent of the activity. So

if(condtion) {

   myViewModel.getSite().observe(this, Observer {
          it?.let {
             println(it.description)
          }
   })

}

As you can see the query needs some parameters (serverId, siteId) that i get them from the Intent. So after i declare myViewModel i pass the parameters in a function setArguments(...) to the viewModel. (I could use ViewModelFactory but the params are not always the same..so forget it)

So the problem is how i should take the site from my repository inside my ViewModel after i have got the arguments

private lateinit var _siteDto: LiveData<SiteDto>
fun setArguments(....) {

 _siteDto = accountsRepository.retrieveSite(serverId, siteId)

}


fun getSite(): LiveData<SiteDto> {
        return _siteDto
    }

When i run it i get the following error
kotlin.UninitializedPropertyAccessException: lateinit property siteDto has not been initialized

james04
  • 1,580
  • 2
  • 20
  • 46

1 Answers1

0

I think your problem is trying to fetch a Livedata object. Livedata is a wrapper! you should return from your database a SiteDTO? object, not a Livedata because you'll receive an instanciated Livedata with a non instanciated SiteDTO inside (which is your current error) ...I suggest you to check out the live data codelabs google has for kotlin (https://codelabs.developers.google.com/android-kotlin-fundamentals/)

Ramiro G.M.
  • 357
  • 4
  • 7