Develop series-API Guides-application components-Activities-Loaders and androidloaders

Source: Internet
Author: User
Tags baseuri

Develop series-API Guides-application components-Activities-Loaders and androidloaders
Loaders

Loaders has the following features:

  • All activities and fragment can be used.
  • Asynchronously load data
  • Monitor Data and distribute data update results
  • When the configuration changes, the previous data cursor is automatically reconnected, and you do not need to query it again.
API Summary
Class/Interface Description
LoaderManager An abstract class associated with activity and frament to manage one or more Loader instances. It is most commonly used in combination with CursorLoader.
Each activity or fragment has only one LoaderManager, but one LoaderManager can operate multiple loaders.
LoaderManager.LoaderCallbacks A callback interface that interacts with LoaderManager. For example, you can use the onCreateLoader () callback method to create a new loader.
Loader An abstract class that executes asynchronous loading of data. You can use CursorLoader in typical cases, but you can also implement your own thunder. When loaders are activated, they should be able to monitor changes to the data source and then generate new results when the data changes.
AsyncTaskLoader An abstract loader that provides AsyncTask for operations.
CursorLoader AsyncTaskLoader subclass, which can query ContentResolver and return a Cursor. This class implements the Loader protocol to query cursors in a standard way. Based on AsyncTaskLoader, it executes the cursor query in the background thread, this will not block the UI. Using this loader is a better way to load data asynchronously.
Use Loaders

Generally, loaders must contain the following information:

  • An activity or fragment
  • LoaderManager instance
  • A CursorLoader loads data through ContentProvider in the background. Of course, you can implement your own Loader or AsyncTaskLoader subclass to load other data sources.
  • LoaderManager. LoaderCallbacks: Create a New loaders and manage existing loaders.
  • A real loader data method, such as SimpleCursorAdapter
  • A data source, such as ContentProvider, when CursorLoader is used.
Start Loader

Generally, the Loader is initialized in the onCreate or fragment onActivityCreated method of the activity:

// Prepare the loader.  Either re-connect with an existing one,// or start a new one.getLoaderManager().initLoader(0, null, this);
  • The first parameter is the unique identifier of loader.
  • Second parameter: Optional
  • The third parameter is the specific implementation of LoaderManager. LoaderCallbacks. The current class implements this interface, so this

The initLoader method has two possibilities:

  • If the loader with the ID 0 already exists, the oader with the last created id 0 will be reused.
  • If the loader with ID 0 does not exist, the onCreateLoader method of LoaderManager. LoaderCallbacks is triggered. here you need to implement code to return the new loader.
Restart Loader

If you need to discard old data, use restartLoader. In the following example, the query conditions change and loadre needs to restart to use the changed query conditions:

public boolean onQueryTextChanged(String newText) {    // Called when the action bar search text has changed.  Update    // the search filter, and restart the loader to do a new query    // with this filter.    mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;    getLoaderManager().restartLoader(0, null, this);    return true;}
Use LoaderManager callback
  • OnCreateLoader: instantiate the Loader based on the new ID and return a new Loader.
  • OnLoadFinished: the previously created loader stops data loading.
  • OnLoaderReset: This method is called when a previously created loader is reset.
Example
Public static class CursorLoaderListFragment extends ListFragment implements OnQueryTextListener, LoaderManager. loaderCallbacks <Cursor> {// adapter SimpleCursorAdapter mAdapter used to display list data; // if not null, use the current filter String mCurFilter; @ Override public void onActivityCreated (Bundle savedInstanceState) {super. onActivityCreated (savedInstanceState); // Give some text to display if there is no data. in a r Eal // application this wocould come from a resource. setEmptyText ("No phone numbers"); // We have a menu item to show in action bar. setHasOptionsMenu (true); // Create an empty adapter we will use to display the loaded data. mAdapter = new SimpleCursorAdapter (getActivity (), android. r. layout. simple_list_item_2, null, new String [] {Contacts. DISPLAY_NAME, Contacts. CONTACT_STATUS}, new int [] {androi D. 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) {// Place an action bar item for searching. menuItem item = menu. add ("Search"); item. setIcon (android. r. drawable. ic_menu_sea Rch); 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 // with this filter. mCurFilter =! TextUtils. isEmpty (newText )? NewText: null; getLoaderManager (). restartLoader (0, null, this); return true ;}@ Override public boolean onQueryTextSubmit (String query) {// Don't care about this. return true;} @ Override public void onListItemClick (ListView l, View v, int position, long id) {// Insert desired behavior here. log. I ("FragmentComplexList", "Item clicked:" + id);} // These are the Contacts rows that we will retri Eve. static final String [] CONTACTS_SUMMARY_PROJECTION = new String [] {Contacts. _ ID, Contacts. DISPLAY_NAME, Contacts. CONTACT_STATUS, Contacts. CONTACT_PRESENCE, Contacts. PHOTO_ID, Contacts. LOOKUP_KEY,}; public Loader <Cursor> onCreateLoader (int id, Bundle args) {// This is called when a new Loader needs to be created. this // sample only has one Loader, so we don't care about the ID. // First, pi Ck the base URI to use depending on whether we are // currently filtering. Uri baseUri; if (mCurFilter! = Null) {baseUri = Uri. withAppendedPath (Contacts. CONTENT_FILTER_URI, Uri. encode (mCurFilter);} else {baseUri = Contacts. CONTENT_URI;} // Now create and return a CursorLoader that will take care of // 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, CONTACTS_SUMMARY_PROJECTION, select, null, Contacts. DISPLAY_NAME + "collate localized asc");} public void onLoadFinished (Loader <Cursor> loader, Cursor data) {// Swap the new cursor in. (The framework will take care of closing the // old cursor once we return .) mAdapter. swapCursor (data);} public void onLoaderReset (Loader <Cursor> loader) {// This is called when the last Cursor provided to onLoadFinished () // above is about to be closed. we need to make sure we are no // longer using it. mAdapter. swapCursor (null );}}



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.