gpt4 book ai didi

android - 如何从 DataSource.Factory 获取数据

转载 作者:行者123 更新时间:2023-11-29 23:19:51 25 4
gpt4 key购买 nike

我必须调用此方法来获取所有人员。我根本无法修改此方法。

@Query("SELECT * FROM PERSON_TABLE ORDER BY NAME DESC"
abstract fun getElements(): DataSource.Factory<Int, Person>

然后在 Activity 中我这样调用它:

override fun onCreate(...)
{
...

val data = dao.getElements()
}

我想得到所有的Person s,可能是一个列表。我该怎么做?

我不明白DataSource.Factory<Int, Person>有效。

最佳答案

根据docs :

Typically, your UI code observes a LiveData object (or, if you're using RxJava2, a Flowable or Observable object), which resides in your app's ViewModel. This observable object forms a connection between the presentation and contents of your app's list data.

In order to create one of these observable PagedList objects, pass in an instance of DataSource.Factory to a LivePagedListBuilder or RxPagedListBuilder object. A DataSource object loads pages for a single PagedList. The factory class creates new instances of PagedList in response to content updates, such as database table invalidations and network refreshes. The Room persistence library can provide DataSource.Factory objects for you, or you can build your own.

示例代码如下:

// The Int type argument corresponds to a PositionalDataSource object.
val data: DataSource.Factory<Int, Person> = dao.getElements()

val dataList: LiveData<PagedList<Person>> = LivePagedListBuilder(data, /* page size */ 20).build()

所以你需要传递你的 DataSource.Factory<Int, Person>反对 LivePagedListBuilder最后你会得到 LiveData<PagedList<Person>>你可以观察到。


之后你需要 connect LiveDataPagedListAdapter如以下代码 fragment 所示:

private val adapter = YourDataAdapter()

override fun onCreate(savedInstanceState: Bundle?) {
dataList.observe(this, Observer { adapter.submitList(it) })
}

您可以找到适配器的示例代码here .

关于android - 如何从 DataSource.Factory 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54561263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com