An application using the loader typically contains the following components:
An activity or fragment.
An instance of loadermanager.
A cursorloader that loads the data supported by contentprovider. Alternatively, you can implement your own Loader from loader or asynctaskloader to load data from other sources.
A loadermanager. loadercallbacks implementation. This is where you create a new loader and manage references of your existing loaders.
A way to display the data of the loader, for example, using a simplecursoradapter.
A Data Source. For example, when cursorloader is used, it will be a contentprovider.
Start a loader
Loadermanager manages one or more loaders in one activiry or fragment, but each activity or fragment only has one loadermanager.
You usually need to initialize a loader in the oncreate () method of activity or the onactivitycreated () method of fragment. You can create it as follows:
// Prepare the loader. You can reconnect an existing one or start a new one. <br/> getloadermanager (). initloader (0, null, this );
The initloader () method has the following parameters:
A unique ID is used to mark the loader. In this example, the ID is 0.
Optional parameter, used when the loader is initialized (null in this example ).
The implementation of loadermanager. loadercallbacks is called by loadermanager to report the events of the loader. In this example, the class library implements this interface, so it transmits its own: This.
Initloader () ensures that a loader is initialized and activated. It has two possible results:
If the loader indicated by ID already exists, the loader will be reused.
If the loader does not exist, initloader () triggers the loadermanager. loadercallbacks method oncreateloader (). This is where you instantiate and return a new loader.
In both cases, the incoming loadermanager. the implementation of loadercallbacks is bound with the loader. it will be called when the loader status changes. if the caller is in the starting status when calling this method, and the requested loader already exists and generates data, the system will immediately call onloadfinished () (that is, in initloader () at execution time ). therefore, you must be prepared for this situation.
Note that initloader () returns the created loader, but you do not need to save a reference to it. loadermanager automatically manages the lifecycle of the loader. loadermanager starts and stops loading as needed, and maintains the status of the loader and its associated content. this means that you rarely interact directly with the loader. you usually use loadermanager. loadercallbacks methods are involved in the data loading process when an event occurs.