从光标onLoadFinished填充部件() [英] Populate widgets from a cursor in onLoadFinished()
问题描述
我想知道如何使用 CursorLoader
来填充屏幕上的小部件。所有的例子在网上只使用一个适配器来完成这项工程。我需要的是一个可靠的方式来更新从游标并在UI线程上,没有有时崩溃,因为 StaleDataException
或光标被停用所有的在我屏幕的意见突然了。这是我目前的做法,但我仍然收到来自用户的一些崩溃报告。
I want to know how to use the CursorLoader
to populate the widgets on a screen. All the examples online are only for using an adapter and this works great. What I need is a reliable way to update the views in my screen from a Cursor and on the UI thread and without sometimes crashing because of StaleDataException
or the cursor being deactivated all of a sudden. Here is my current approach but I still receive some crash reports from users.
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle arg1) {
CursorLoader loader = null;
switch (id) {
case LOADER_ID_DATA:
loader = new CursorLoader(...);
break;
}
return loader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, final Cursor cursor) {
handler.post(new Runnable() {
@Override
public void run() {
if (getActivity() == null)
return;
updateView(cursor);
}
});
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
}
一个解决办法是直接检索所有光标领域内onLoadFinished和它们传递到处理程序,以填充小部件的UI线程。但是,这是丑陋的,因为我可以有很多值的光标。我很想找到应对这一切的可靠的碰撞自由的方式。
One solution would be to retrieve all the cursor fields directly inside onLoadFinished and pass them all to the handler to populate the widgets on the UI thread. But this is ugly because I may have a lot of values in the cursor. I would love to find a reliable crash-free way of dealing with all this.
推荐答案
要求在#后的Android开发 SimonVT
和自述
帮助我拿到这条底线。
After asking on #android-dev SimonVT
and readme
helped me to get the bottom of this.
没有什么,指出 onLoadFinished
将被称为UI线程因此从理论上讲,你应该使用处理程序
建议一样在雷托的书。然而,当使用 CursorLoader
(这是迄今为止最常见的情况),您可以pretty的多少保证 onLoadFinished
将被称为在UI线程。
There is nothing that states that onLoadFinished
will be called on the UI thread so in theory you should use a Handler
like advised in Reto's book. However, when using a CursorLoader
(which is by far the most common use case) you can pretty much guarantee that onLoadFinished
will be called in the UI thread.
这篇关于从光标onLoadFinished填充部件()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!