我正在浏览我的一些代码,但我意识到我实际上并不知道 CursorLoader
和 LoaderManager
组合如何与 CursorAdapter
一起使用> 连接。这是我感到困惑的部分。
agendaAdapter = new MyAgendaAdapter(this, null);
makeProviderBundle(new String[] {"_id", "event_name", "start_date", "start_time",
"end_date", "end_time", "location"}, "date(?) >= start_date and date(?) <= end_date",
new String[]{getChosenDate(), getChosenDate()}, null);
getLoaderManager().initLoader(0, myBundle, MainDisplayActivity.this);
list.setAdapter(agendaAdapter);
那么,我的自定义 ContentProvider
中的 query()
方法如何知道将其发送到特定的 CursorAdapter
?我只是没有看到联系。我了解其中的所有其他内容,但这个问题是关于什么的。哦,我应该提一下,代码运行良好。
最佳答案
首先,查看 this post 的代码示例和 this post更深入地了解该过程的工作原理。
现在,回答您的问题...
How does the query() method from my custom
ContentProvider
...?
嗯,首先要记住 getContentResolver().query()
不调用内容提供者的 query
直接方法。您正在调用内容解析器的查询方法,该方法解析 Uri
,确定您希望调用的提供程序,然后然后调用您的提供程序的query
方法.
How does the query get sent to that specific
CursorAdapter
?
我将使用 API Demos 引导您完成整个过程举个例子。请注意,API 演示使用 ListFragment
而不是 ListActivity
(在这个问题的背景下,差异并不重要)。
首先,创建(并设置)
CursorAdapter
。mAdapter = new SimpleCursorAdapter( getActivity(), android.R.layout.simple_list_item_2, null, new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS }, new int[] { android.R.id.text1, android.R.id.text2 }, 0);
执行此语句后,
SimpleCursorAdapter
知道它应该如何将游标数据与您的 View 相关联。无论光标的Contacts.DISPLAY_NAME
中有什么数据列将与 ID 为android.R.id.text1
的 View 相关联等。请注意,您已通过
null
cursor 作为构造函数的第三个参数。这非常重要,因为我们还没有查询任何数据(这是LoaderManager
和CursorLoader
的工作)。接下来,初始化加载器。
getLoaderManager().initLoader(0, null, this);
这告诉
LoaderManager
创建并启动Loader
对应id0
.LoaderManager
来电onCreateLoader(int id, Bundle args)
.onCreateloader
返回Loader<Cursor>
的子类接口(interface)(即CursorLoader
,在这种情况下)。这个CursorLoader
将执行初始查询,并在数据更改时自行更新。如果您的 Activity/fragment 有多个加载程序,那么您将使用
switch(id)
以确定已指示开始加载过程的特定加载程序。查询到的游标传给
onLoadFinished()
.紧接在
CursorLoader
之后在步骤 3 中实例化并返回CursorLoader
在单独的线程上执行初始查询并返回游标。当CursorLoader
完成查询,将新查询的游标返回到LoaderManager
,然后将光标传递到onLoadFinished
方法。在文档中,“onLoadFinished
方法在先前创建的加载程序完成加载时被调用。”查询到的数据与
CursorAdapter
相关联。mAdapter.swapCursor(data);
请注意
onLoadFinished
通常也是您使用查询数据更新 Activity/fragment 的 UI 的地方。在这种情况下这不是必需的,因为我们之前称为setListAdapter(mAdapter)
.ListFragment
知道如何使用CursorAdapter
(见步骤 1)... 我们需要做的就是将光标传递给适配器swapCursor
,以及ListFragment
将为我们在屏幕上显示数据。
如果您有任何问题(或者是否有任何拼写错误等),请告诉我。
TL;DR
包含查询数据的游标与 CursorAdapter
相关联在 onLoadFinished
.这通常通过调用 mAdapter.swapCursor(data)
来完成。 .
关于android - 带 LoaderManager 的 CursorLoader 如何知道将光标发送到 CursorAdapter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11150527/