Android Loaders

Loaders are part of Android since Honeycomb and were added to the support library so they are available on any Android release.
Loaders provide a framework to perform asynchronous loading of data.
They are registered by ID, with a component called the LoaderManager, which allows them to live beyond the life cycle of the Activity they are associated with.

This prevents duplicate loads from happening in parallel (problem of AsyncTasks).
If we want to load data on a background thread we can use an implementation of a loader pattern called AsyncTaskLoader.
The AsyncTaskLoader implements the same functionality as AsyncTask, but because it is a Loader then its life cycle is different.
Why should you use Loaders?
1. Run on a separate thread -> better UI performance
2. Have their independent life cycles -> Goes beyond the Activity life cycle
3. Simplify thread management by provoking callback methods when events occur
4. Persist and cache results to prevent duplicate queries
5. Can implement an observer to monitor for changes in the underlying data source
In quick words, to implement a Loader you have to implement the LoaderCallbacks methods (onCreateLoader, onLoadFinished, onLoaderReset) and register your loader with the LoaderManager.
The LoaderManager is responsible for managing one or more Loaders associated with an Activity or Fragment.
Each Activity or Fragment has exactly one LoaderManager instance that is in charge of starting, stopping, retaining, restarting and destroying its Loaders.
Initializing a loader is very simple. After implementing the LoaderCallbacks you simply do the following:
getLoaderManager().initLoader(loader id, bundle arguments, class implementing the LoaderCallbacks interface);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s