Loaders In Android (Part 1)
What is a Loader?
Loader is a set of APIs, known as Loader APIs given by Android, to load data asynchronously in activity/fragment.
What is the Use of Loader?
It can fetch data asynchronously without blocking the main thread and it manages it's own lifecycle during
onDestroy() and configuration changes.
How Do I Use it?
Loaders in Android is an abstract class implementation of Loader and two default classes, which are provided by Android, I.E.
AsyncTaskLoader, and cursor loaders.
There is only one Loader instance per activity/fragment and is created by Loader managers.
LoaderManager can manage multiple instances of Loaders.
There are three main parts to implement loader with Android:
LoaderManager is used to initialize loaders in activity/fragment. Loaders can be initialized mainly in
onCreate () /
onStart () , functions by using
LoaderManager. init(LOADER_ID,OPTION_ARGUMENT,CALLBACK_CLASS_REFERNCE) and
The three arguments that will into
restartLoader() function are as follows:
LOADER_ID: Uniq ID given to Loader, if we are initializing Loader, will check if the Loader ID is present or not. It will call on the callbacks method accordingly, which I wil explain later.
OPTION_ARGUMENT: It is the argument given to Loader at the time of initialization.
CALLBACK_CLASS_REFERENCE: Class that implements all it's callback function, which Loader will return data.
init() will initialze the Loader ID and call
onCreateLoader() (will explain this later) , when no Loader with Loader ID is present, and if Loader is already present, it will call
restartLoader() will invalidate the previous data and restart the Loader with new Loader reference.
It provide a set of three methods which Loader with call sequentially:
OnCreateLoader(int,bundle): We will call on this method when we initialize Loader. In can only be called when no Loader with LOADER_ID is already present.
onCreateLoader()will return the Loader object, either
OnLoadFinished(): Called after our data loading is finished. Basically we'll do all the user interface binding and other things here.
OnLoaderReset(): Every time our Loader gets reset (either activity/ Fragment get destroyed), we have to clear all the refereces from current Loader in this callback.
Loader is the abstract class, which serves as a base class for all the Loaders. There are two implementation given by Android:
AsyncTaskLoader: A Loader that provides
AsyncTaskto perform background operations.
CusorLoader: A Loader implementation used to get data from content providers through content resolvers.
Here are a few links you might find useful!
- Loader in Android - includes more ideas for topics
You can write to me for any suggestions [ashish. Bangar. Iiitm@gmail. Com] (mailto: Ashish. Bangar. Iiitm@gmail. Com) !