How to transition from managedQuery to LoaderManager/CursorLoader?

半城伤御伤魂 提交于 2019-11-28 05:04:56

Edit:

I've written fairly extensively about the LoaderManager in this blog post. Check it out and let me know if its helpful! :)


Original post:

Definitely, definitely, definitely go with LoaderManager. The CursorLoader class offloads the work of loading data on a thread, and keeps the data persistent during short term activity refresh events, such as an orientation change. In addition to performing the initial query, the CursorLoader registers a ContentObserver with the dataset you requested and calls forceLoad() on itself when the data set changes, and is thus auto-updating. This is extremely convenient as you don't have to worry about performing queries yourself. Of course it is possible to make use of AsyncTask to keep your application UI thread friendly, but it will involve a lot more code... and implementing your class so that it will, for example, retain the loaded Cursor over Activity won't be simple. The bottom line is that LoaderManager/Loader will do this automatically for you, as well as taking care of correctly creating and closing the Cursor based on the Activity lifecycle.

To use LoaderManager/CursorLoader in an app targeting a pre-11 API level, simply use the FragmentActivity class in the compatibility package. A FragmentActivity is just an Activity and has been created for Android compatibility support, and does not require the use of Fragments in your application. Just use getSupportLoaderManager() instead of getLoaderManager() and you should be all set. You could, of course, implement a parent FragmentActivity for each screen and have it displays a its layout in a Fragment (by making use of FragmentActivity.getSupportFragmentManager() in the Activity's onCreate() method). This design might make the transition to multi-pane layouts easier if you ever decide to optimize your application for tablets. It's a nice learning experience too :).

This is a pretty nice tutorial too. Try and work your way through it and don't hesitate to leave a comment if you have any other questions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!