房间查询返回空值

房间查询返回空值

本文介绍了房间查询返回空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的查询:

在这里,当我检索它时,valuenull:

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

我已经调试了数据库,数据在那里:

I have debugged my database and the data is there:

这是我的实体对象:

我已经调查了数据库查询,但是无法弄清楚出了什么问题

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

推荐答案

您的查询返回LiveData.您将不得不观察这些变化.最初,查询前该值为null.查询后,列表数据集将更改,它将为您返回所需的正确值.

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.

假设ViewModel类是这样的:

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
    }
}

在Activity类中,您可以通过以下方式观察列表:

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")
        })
    }
}

这篇关于房间查询返回空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 02:03