Room query returns null value

梦想的初衷 提交于 2020-06-17 09:43:13

问题


This is my query:

and here, when I retrive it, the value is null :

I have debugged my database and the data is there:

This is my entity object :

I have investigated the database query, but couldn't figure what's wrong


回答1:


Your Query returns a LiveData. You will have to observe the changes. Initially, the value is null before the query. After the query, the list dataset changes and it will return you the desired correct values.

Assuming ViewModel class is something like this:

class MyViewModel:ViewModel(){
    private val gymDao: GymDao
    private val listLiveData: LiveData<List<Country>>

    init {
        val roomDatabase = myRoomDatabase.getDatabase(application)
        gymDao= roomDatabase ?.gymDao()!!
        listLiveData = gymDao?.getCountriesList()
    }

    fun getAllCountries(): LiveData<List<Country>> {
        return listLiveData
    }
}

In your Activity class, you can observe the list as:

class MyActivity : AppCompatActivity() {
    private lateinit var vm: MyViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.my_activity)

        vm = ViewModelProviders.of(this).get(MyViewModel::class.java)

        vm.getAllCountries().observe(this, Observer { items ->
            if (!items.isEmpty()) {
                Log.d(TAG, "ITEMS: $items")
            }

            Log.d(TAG, "ITEMS: $items")
        })
    }
}


来源:https://stackoverflow.com/questions/61914751/room-query-returns-null-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!