6

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

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.

4

1 回答 1

7

在询问#android-devSimonVTreadme帮助我了解这一点之后。

没有任何声明onLoadFinished将在 UI 线程上调用,因此理论上您应该使用HandlerReto 书中建议的类似方法。但是,当使用 a CursorLoader(这是迄今为止最常见的用例)时,您几乎可以保证onLoadFinished将在 UI 线程中调用它。

于 2012-05-18T10:31:32.037 回答