This will be my fourth and final post on Loaders and the LoaderManager. Let me know in the comments if they have been helpful! Links to my previous Loader-related posts are given below:
- Part 1: Life Before Loaders
- Part 2: Understanding the LoaderManager
- Part 3: Implementing Loaders
- Part 4: Tutorial: AppListLoader
Due to public demand, I've written a sample application that illustrates how to correctly implement a custom Loader.
The application is named AppListLoader,
and it is a simple demo application that queries and lists all installed applications on your Android device.
The application is a modified, re-thought (and bug-free) extension of the
sample that is provided in the API Demos. The application uses an
(a subclass of
AsyncTaskLoader) to query its data, and the LoaderManager to
manage the Loader across the Activity/Fragment lifecycle:
The AppListLoader registers two
BroadcastReceivers which observe/listen for system-wide broadcasts that
impact the underlying data source. The
InstalledAppsObserver listens for newly installed, updated, or
removed applications, and the
SystemLocaleObserver listens for locale changes. For example, if the user
changes the language from English to Spanish, the
SystemLocaleObserver will notify the AppListLoader to
re-query its data so that the application can display each application's name in Spanish (assuming an alternate
Spanish name has been provided). Click "Change language" in the options menu and watch the Loader's seamless
reaction to the event (it's awesome, isn't it? :P).
Log messages are written to the logcat whenever an important Loader/LoaderManager-related event occurs, so be sure to run the application while analyzing the logcat! Hopefully it'll give you a better understanding of how Loaders work in conjunction with the LoaderManager and the Activity/Fragment lifecycle. Be sure to filter the logcat by application name ("com.adp.loadercustom") for the best results!
You can download the application from Google Play by clicking the badge below:
The source code is available on GitHub. An excessive amount of comments flesh out the entire application-Loader workflow. Download it, import it as an eclipse project, and modify it all you want!
Let me know if these posts have been helpful by leaving a comment below! As always, don't hesitate to ask questions either!