The loaders mechanism was introduced after the Android 3.0 release. The loaders mechanism makes it easier for an activity or a fragment to load data asynchronously. Loaders has the following characteristics:
Ø they apply to any activity and fragment;
Ø they provide a mechanism for loading data asynchronously;
Ø They detect data sources, and they can pass new results when the content of the data source changes;
Ø when re-creation is required after configuration changes, they reconnect to the last loader cursor. In this way, they do not need to requery their data.
1 Loader API Summary
There are many classes and interfaces associated with loaders that can be used in the app. Summarized as follows:
|
class/interface |
description |
|
Loadermanager |
An abstract class that is associated with activity and fragment for managing one or more loader instances. This helps the app manage long running operations. The most notable example of using it is cursorloader. Each activity or fragment can have only one loadermanager. And a loadermanager can have multiple loaders. |
|
loadermanager.loadercallbacks |
A callback interface that is provided to the client for interaction with Loadermanager. For example, you can use Oncreateloader () callback to create a new loader. |
|
Asynctaskloader |
An abstract loader that provides a asynctask to work on. |
|
Cursorloader |
Asynctaskloader subclasses, Used to request to Contentresover, returns a cursor. This class implements the loader protocol in the form of a standard cursor query, establishes a asynctaskloader, uses a background thread to query the cursor, and does not block the app's UI. Therefore, using this loader is the best way to load asynchronous data from ContentProvider. |
The class and interface above are the components you need to implement a loader in your app. You don't have to use all the components, but you usually need a loadermanager reference (for initializing a loader) and a loader implementation class (such as Cursorloader).
2 using loaders in the app
In an app, the typical use of loaders contains the following:
An activity or a fragment.
An instance of a loadermanager.
A cursorloader, loading data from a contentprovider.
An implementation of a loadermanager.loadercallbacks. In this you create new loader, and manage already existing loaders.
A way to display loader loading data, such as Simplecursoradapter.
A data source, such as a conterprovider (when using Cursorloader).
2.1 Starting a Loader
In an activity or fragment, Loadermanager manages one or more loader instances. There is only one loadermanager per activity or fragment.
You can initialize a loader in the OnCreate () method in the activity, or in the onactivitycreated () method in fragment. For example:
|
Prepare the loader. Either re-connect with an existing one,
Or start a new one.
Getloadermanager (). Initloader (0,null, this); |
The Initloader () method has three parameters:
Ø a flag loader ID.
Ø the parameters provided to the loader constructor are optional.
Ø the realization of a loadermanager.loadercallbacks.
The invocation of Initloader () ensures that a loader is initialized and activated. It has two kinds of results:
If the ID of the flag loader already exists, the last created loader is reused.
If the ID of the flag loader does not exist, Initloader () fires the Loadermanager.loadercallbacks Method Oncreateloader ().
In both cases, the given Loadermanager.loadercallbacks instance is associated to loader and is called when the loader state changes. If the caller is in its starting state and the requested loader already exists and the data has been generated, then the system immediately calls Onloadfinished () (During the Initloader () call), so you must be prepared for this to happen.
Remember, Intiloader () returns a created loader, but you don't need to get a reference to it. Loademanager automatically manages the life cycle of the loader. Loadermanager will start loading, end loading, maintain the status of loader, and related content. This means that you rarely have to interact directly with loaders. When a particular event occurs, you simply need to use the Loadermanager.loadercallbacks method to intervene in the loading process.
2.2 Restarting a Loader
When you call a Initloader (), as shown above, you will get an ID already exists for loader, or create a new loader. But sometimes you want to throw away your old data and start over again.
To discard your old data, you need to call Restartloader (). For example, the implementation of Searchview.onquerytextlistener restarts the loader when the user's query changes. Loader requires a reboot because it is using a modified search filter to make a new query:
public boolean onquerytextchanged (String newtext) { //called when the Action Bar search text has changed. Update //The search filter, and restart the loader to does a new query //with this filter. Mcurfilter =! Textutils.isempty (NewText)? Newtext:null; Getloadermanager (). Restartloader (0, NULL, this); return true; } |
2.3 Using Loadermanagercallbacks
Loadermanager.loadercallbacks is the callback interface that provides the client with an interface to interact with the Loadermanager.
Loaders, especially Cursorloader, are expected to be able to maintain their data after being stopped. This allows apps to keep their data in the OnStop () and OnStart () methods of actvitiy or fragemnt without waiting for the data to be reloaded. You use the Loadermanager.loadercallbacks method to know when to create a new loader and tell the apps when to stop using a loader data.
The loadermanager.loadercallbacks contains three methods:
Oncreateloader ()---Instantiate and return a newly created loader of the given ID
Onloadfinished ()---when a created loader completes the load, call this function
Onloaderreset ()---when a created loader is to be reset, call this function, which causes its data to be invalid
2.3.1 Oncreateloader
When you try to access a loader (for example, through Initloader ()), it checks whether the ID of the given loader exists. If it does not exist, it will trigger the method Oncreateloader () in Loadermanager.loadercallbacks to create a new loader. The typical example is Cursorloader.
In this example, the Oncreateloader () callback function creates a cursorloader. You must use the Cursorloader constructor, which requires some additional information to query a contentprovider. It requires:
URI---Gets the URI of the content.
Projection---The list of columns to return. Passing NULL returns all columns, which is not efficient enough.
Selectionargs---You might want to include s in selection, replaced by values in Selectionargs.
SortOrder the order of---rows is formatted by the SQL ORDER by statement. Passing NULL returns the default sort, perhaps unordered.
For example:
If Non-null, the current filter of the user has provided. String Mcurfilter; loader<cursor> oncreateloader (int id, Bundle args) { //This is called when a new Loader needs to be created. this //sample only have one Loader, so we don ' t care about the ID. //First, pick the base URI to use depending on whether we is //currently filtering. Uri BaseUri; if (mcurfilter! = null) { BaseUri = Uri.withappendedpath (contacts.content_filte R_uri, Uri.encode (mcurfilter)); } else { BaseUri = Contacts.content_uri; } //Now Create and return a cursorloader that'll take care of //creating A Cursor for the data being displayed. String select = "((" + Contacts.display_name + "NotnulL) and (" + contacts.has_phone_number +" =1) and (" &NBSP ; + Contacts.display_name + "! =") "; return new Cursorloader (Getactivity (), BaseUri, Contacts_summary_ PROJECTION, select, NULL, Contacts.display_name + "COLLATE localized ASC"); } |
2.3.2 onloadfinished
This method is called when a well-created loader ends its load. This method ensures that the data maintained by the loader is freed before being called. At this point, you should remove all use of the old data (because the old data will be released soon) without releasing the old data, loader will complete the release of the old data.
Loader once you know that the app is no longer using it, it will release the data. For example, if the data is from a cursor in cursorloader, you should not call Close () yourself. If a cursor is being placed into a cursoradapter, you should use the Swapcursor () method so that the old cursor is not turned off.
For example:
The Adapter being used to display the list ' s data. Simplecursoradapter Madapter; ... public void onloadfinished (loader<cursor> Loader, Cursor data) { //swaps the new Cursor in. (The framework would take care of closing the //old cursor once we return.) Madapter.swapcursor (data); } |
2.3.3onLoaderReset
This method is called when the established loader is being restarted, which puts the loader data in an invalid state. This callback function lets you find out when the data is going to be released, and at that point you can remove the reference to it.
For example:
The Adapter being used to display the list ' s data. Simplecursoradapter Madapter; ... public void Onloaderreset (loader<cursor> Loader) {//This was called when the last Cursor provided to OnLoad Finished () ///above is on to being closed. We need to make sure we is no //longer using it. Madapter.swapcursor (null); } |
3 examples
This example is an fragment implementation that uses the ListView to display the results of the Address Book query and uses Cursorloader to manage queries provider the address book. If the app needs to access the Address book, you need to add permission read_contacts to the mainfest.
public static class Cursorloaderlistfragment extends Listfragment implements Onquerytextliste NER, loadermanager.loadercallbacks<cursor> { //This was the Adapter being used to display the list ' s data. Simplecursoradapter Madapter; //If Non-null, the current filter the user has provided. String Mcurfilter; @Override public void onactivitycreated (Bundle savedinstancestate) { Super.onac Tivitycreated (savedinstancestate); //Give some text to display if there is no data. in a real //Application This would come from a resource. Setemptytext ("No phone Numbers"); //We have a menu item to show in action Bar. Sethasoptionsmenu (true); //Create an empty adapterWe'll use to display the loaded data. Madapter = new Simplecursoradapter (getactivity (), & nbsp Android. R.layout.simple_list_item_2, NULL, new string[] {Contacts.displa Y_name, Contacts.contact_status}, New int[] {Android. R.id.text1, Android. R.ID.TEXT2}, 0); Setlistadapter (madapter); //Prepare the loader. either re-connect with an existing one, //or start a new one. Getloadermanager (). Initloader (0, NULL, this); @Override public void Oncreateoptionsmenu (Menu menu, Menuinflater inflater) { &NB Sp /Place a action bar item for searching. MenuItem item = menu.add ("Search"); &NBSP; Item.seticon (Android. R.drawable.ic_menu_search); item.setshowasaction (menuitem.show_as_action_if_room); Searchview SV = new Searchview (getactivity ()); Sv.setonquerytextlistener (this); Item.setactionview (SV); public boolean onquerytextchange (String newtext) { //called When the Action Bar search text has changed. update //The search filter, and restart the loader to do a new query &N Bsp //With the This filter. Mcurfilter =! Textutils.isempty (NewText)? Newtext:null; Getloadermanager (). Restartloader (0, NULL, this); return true; @Override public boolean onquerytextsubmit (String query) { / /Don' t care on this. return true; } @Override public void Onlistitemclick (ListView l, View v, int position, long id) {&NBSP ; //Insert desired behavior here. LOG.I ("Fragmentcomplexlist", "Item clicked:" + ID); //These is the Contacts rows that we'll retrieve. static final string[] contacts_summary_projection = new string[] { CONTACTS._ID , Contacts.display_name, Contacts.contact_status, Contacts.contact_presence, contacts.photo_id, Con Tacts. Lookup_key, }; Public loader<cursor> Oncreateloader (int. ID, Bundle args) { //This is CA lled when a new Loader needs to be created. this //sample only have one Loader, so we don ' t care is about the ID. //First, pick the base URI to use depending in whether we are // Currently filtering. Uri BaseUri; if (mcurfilter! = null) { BaseUri = Uri.withappende Dpath (Contacts.content_filter_uri, Uri.encode (Mcurf Ilter)); } else { BaseUri = Contacts.content_uri; } //Now Create and return a cursorloader that'll take care O F //Creating a Cursor for the data being displayed. String select = "((" + Contacts.display_name + "notnull) and (" + ContaCts. Has_phone_number + "=1" and (" + Contacts.display_name +"! = " ))"; return new Cursorloader (Getactivity (), BaseUri, &NB Sp Contacts_summary_projection, select, NULL, CONTACTS.DISPLA Y_name + "COLLATE localized ASC"); public void onloadfinished (loader<cursor> Loader, Cursor data) { &NB Sp /Swap the new cursor in. (the framework would take care of closing the //old C Ursor once we return.) madapter.swapcursor (data); public void Onloaderreset (loader<cursor> Loader) { // This was called when the last Cursor provided to onloadfinished () //above are about to be Clos Ed w.e need to make sure we is no //longer using it. madapter.swapcursor (null); }} |
For more examples, refer to "Loadercursor" and "Loaderthrottle" in API demos.
Advanced The loaders mechanism in Android