Simple and practical Android Loader Technology

Source: Internet
Author: User

Simple and practical Android Loader Technology

Since Android3.0, Android SDK provides the Loader technology, which makes it easy to load data asynchronously. The Loader technology provides the following core classes:

  • LoaderManager: You can obtain LoaderManager through the getLoaderManager () method of Activity or Fragment to manage Loader. One Activity or Fragment can only have one LoaderManager.
  • LoaderManager. LoaderCallbacks: used for interaction with LoaderManager, where you can create a Loader object.
  • AsyncTaskLoader: an abstract class that can load data asynchronously. It seems that it is also implemented internally through AsynTask. You can inherit it to build your own Loader, or use an existing subclass, for example, you can use CursorLoader to asynchronously query a database.

    To use Loader, follow these steps:

    1. initialize Loader. You can use initLoader (intid, Bundle args, LoaderManager. LoaderCallbacks Callback); Method for initialization.
    Id: ID of the Loader. One Activity or Fragment can have only one LoaderManager, but multiple loaders can be located by ID. When creating a Loader, if a Loader with the same ID is found, the Loader will be reused without re-creation.
    Args: The parameter passed to the new Loader.

    Callback: Callback interface.


    2. Implement the methods in LoaderManager. LoaderCallbacks. The methods to be implemented in LoaderManager. LoaderCallbacks include:
    PublicLoader OnCreateLoader (int id, Bundle args): Creates a new Loader whose id is LoaderID. If a Loader with the same ID already exists, the Loader will be reused instead of re-created. Args is the parameter passed during initialization. This method starts asynchronous query and returns a generic class. If you are querying a database, you can return a CursorLoader and a custom Loader. Public voidonLoadFinished (Loader Loader, D data): This method is called when the asynchronous query ends and the query result data is returned. Public void onLoaderReset (Loader Loader): When you call Loader. when reset () clears the Loader data, the system automatically calls the Loader when the system destroys the Loader. reset () method. Generally, you do not need to call it manually. You only need to remove Loader from the onLoaderReset method.

    3. Use restartLoader (intid, Bundle args, LoaderManager. LoaderCallbacks Callback) method to update the data, and initialize one. If a Loader with the same id exists, the Loader will be reused and the data in the original Loader will be cleared. If not, a new Loader will be created. This method is generally used when data needs to be updated. For example, in the following example, you need to call this method to query data asynchronously when searching for key changes.


    The following example uses CursorLoader to query the contact name and display it in ListActivity. A SearchView is placed on the ActionBar to query the contact by the contact name keyword.

    The Activity code is as follows:

    Public class MainActivity extends ListActivity implements LoaderManager. LoaderCallbacks
          
           
    , 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 wait"); 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
           
            
    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 a Loader object and start loading data asynchronously. return new CursorLoader (this, uri, pro, null );} @ Override public void onLoadFinished (Loader
            
             
    Loader, Cursor data) {// get asynchronously loaded data, update Adapter cursorAdapter. swapCursor (data) ;}@ Override public void onLoaderReset (Loader
             
              
    Loader) {// remove the Loader used by the adapter. The system releases the Loader cursorAdapter that is no longer in use. 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 (clear the old data) getLoaderManager (). restartLoader (0, null, this); return false ;}}
             
            
           
          

    Menu resource file:

              
           
          

    Last:




  • Related Article

    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.