Fill widgets with cursor in onLoadFinished ()

I want to know how to use CursorLoader to populate widgets on the screen. All online examples are only available for using the adapter, and this works great. I need a reliable way to update the views on my screen using the cursor and the user interface thread and without breaking due to a StaleDataException or a sudden cursor deactivation. Here is my current approach, but I still get 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 get all the cursor fields directly inside onLoadFinished and pass them to all the handler to populate the widgets in the user interface thread. But this is ugly because I can have many values ​​in the cursor. I would like to find a reliable way to handle all this without any problems.

+6
source share
1 answer

After requesting # android-dev SimonVT and readme I managed to get the bottom of this.

There is nothing to indicate that onLoadFinished will be called in the user interface thread, so theoretically you should use Handler , as described in the Reto book. However, when using CursorLoader (which is by far the most common use case), you can pretty much guarantee that onLoadFinished will be called in the user interface thread.

+7
source

Source: https://habr.com/ru/post/912931/


All Articles