Simple and practical Android Loader technology

Source: Internet
Author: User

Starting with Android3.0, the Android SDK provides loader technology that makes it easy to asynchronously load data using loader technology. Loader technology provides us with the following core classes:

    • Loadermanager: Can be loadermanager by activity or the Getloadermanager () method of fragment, used to manage loader, An activity or fragment can only have one loadermanager.
    • loadermanager.loadercallbacks: Used to interact with Loadermanager, where you can create loader objects.
    • Asynctaskloader: Abstract class, can be asynchronous loading data loader, seemingly internal also through Asyntask implementation, you can inherit it to build their own loader, you can also use the existing subclasses, For example, an asynchronous query database can use Cursorloader.

The following steps can generally be used with loader:

1, initialize the loader, you can use Initloader (IntID, Bundle args, Loadermanager.loadercallbacks<d> callback) method to initialize.
ID: Identifies the ID of the loader, an activity or fragment can have only one loadermanager, but may have multiple loader, differentiated by ID. When you create a new loader, if you find a loader that already has the same ID, the loader will be reused and not recreated.
Args: Parameters passed to the new loader.

Callback: Callback interface.


2, the implementation of Loadermanager.loadercallbacks in the method, loadermanager.loadercallbacks need to implement the methods are:
    • publicloader<d> Oncreateloader (int id, Bundle args) : Creates a new loader,id for Loaderid, and if a loader already has the same ID, the loader will be reused and not recreated. Args is the parameter passed at initialization time. The method begins an asynchronous query and returns a generic class, and if the query database can return a cursorloader, the custom loader can be returned.
    • public Voidonloadfinished (loader<d> Loader, D data) : This method is called at the end of the asynchronous query and returns the query result data.
    • public void Onloaderreset (loader<d> Loader) : The Loader () method is automatically called when Loader.reset () is called to empty the Loader data, but when the system destroys Loader.reset We generally do not need to call manually, only in the Onloaderreset method, you will use the loader removal.

3, using Restartloader (IntID, Bundle args, Loadermanager.loadercallbacks<d> callback) method for data update, and initialization of one, If a loader with the same ID exists, the loader is reused and the data in the original loader is emptied, and if not, a new one is created. This method is typically used when you need to update the data, for example, in the following example, when searching for key changes, you need to call this method to query the data from the new asynchronous.


The following example uses Cursorloader to query the contact name and displays it in Listactivity, where a searchview is placed on the Actionbar to query the contact based on the contact's name keywords.

The activity code is as follows:

public class Mainactivity extends listactivity implements LOADERMANAGER.LOADERCALLBACKS&LT;CURSOR&GT;    Searchview.onquerytextlistener {private Simplecursoradapter cursoradapter;    Private String Filtername=null;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main); TextView tv= (TextView) Findviewbyid (Android.        R.id.empty);        Tv.settext ("please later"); Cursoradapter=new Simplecursoradapter (this, Android.                R.layout.simple_list_item_2, NULL, new String[]{contactscontract.contacts.display_name}, New Int[]{android.         r.id.text1},0);        Setlistadapter (CursorAdapter);    Initialize loader getloadermanager (). Initloader (0,null,this);        } @Override public loader<cursor> oncreateloader (int id, Bundle args) {URI uri; String[] Pro=new string[]{contactscontract.contacts.display_name,contactSCONTRACT.CONTACTS._ID};        if (Textutils.isempty (filtername)) {uri= ContactsContract.Contacts.CONTENT_URI;        }else{Uri=uri.withappendedpath (Contactscontract.contacts.content_filter_uri,uri.encode (filterName));    }//Create loader object, start loading data asynchronously return new Cursorloader (This,uri,pro, NULL, null,null);        } @Override public void onloadfinished (loader<cursor> Loader, Cursor data) {//Get asynchronous Load data, update adapter    Cursoradapter.swapcursor (data);        } @Override public void Onloaderreset (loader<cursor> Loader) {//Remove Loader used by adapter, the system will release Loader that is no longer in use    Cursoradapter.swapcursor (NULL);         @Override public boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.menu_main,menu);        Searchview v= (Searchview) Menu.finditem (r.id.menu_search). Getactionview ();        V.setonquerytextlistener (this);    return true; } @Override public boolean onquerytextsubmit (String query){return true;        } @Override public boolean onquerytextchange (String newtext) {filtername=newtext;        Use the new loader (empty old data) Getloadermanager (). Restartloader (0,null,this);    return false; }}

Menu resource file:

<menu xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http://schemas.android.com /tools "tools:context=". Mainactivity ">    <item android:actionviewclass=" Android.widget.SearchView "        android:id=" @+id/menu_ Search "        android:showasaction=" Ifroom|collapseactionview "        android:title=" searches "        tools:ignore=" Appcompatresource "/></menu>

Finally, here's a:




Simple and practical Android Loader technology

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.