Android asynchronous database of loaded weapon --Loaders

English document Source: http://developer.android.com/guide/components/loaders.html

Loaders, Chinese understood as a "loader", add in the Android3.0. Its function can be seen from the literal meaning, i.e. providing data loading. In particular, the asynchronous data loading mode. It has the following features:

  • Loaders and Fragment Activity for all;
  •  Providing asynchronous data loading mechanism;
  • Monitor their source data changes, the new results at the time of the transfer of data changes;
  • Automatic reconnect to the last cursor data loader, there is no need to re-query data


How to use in the application Loaders

Use Loaders prerequisite:

  • Activity or need a Fragmnet
  • Examples of a LoaderManager
  • CursorLoader object for loading data (dependent on the ContentProvider)
  • A LoaderManager.LoaderCallbacks implementation class.
  • A data display adapter, such as SimpleCursorAdapter
  • A data source, such as ContentProvider

Start the data loader Loaders

Activity LoaderManager a manager or one or more of the Fragment Loader instance, each correspond to only a Activity or Fragment LoaserManager.
         Activity is generally onActivityCreated onCreate method or method of initializing a Fragment Loader:
getLoaderManager () initLoader (0, null, the this);.
Parameters:

1, the first parameter: 0 is the unique identification ID Loader;
2, the second parameter: optional constructor parameters Loader, here null;
. 3, the third parameter: the this, means the current object or Activity Fragment objects, the object data supplied to LoaderManager reporting.
InitLoader () method to ensure that the Loader initialization and object activation, implementation of this approach has two possible outcomes:

1, if the ID is present, the reuse;
2, if the ID does not exist, then the departure of LoaderManager.LoaderCallbacks onCreateLoader () to create a new method and returns Loader;


In any case, only Loader status has changed, LoaderManager.LoaderCallbacks associated with implementation class will be told;

You may have noticed, Loader objects initLoader returned not associated with any variable, it is because there is an automatic LoaderManager Loader management functions; LoaderManager start and stop data loading operation automatically when necessary, and defenders Loader state; this It means that you rarely interact directly with the Loader. In general, the use of LoaderManager.LoaderCallbacks onCreateLoader () method to intervene in the process of data loading in special events.


How to restart the data loader Loaders

When you create Loaders above, if the ID does not exist, create, or use the old Loader, but sometimes, we need to clean out the old data is restarted.
Use restartLoaser () can be done. For example, SearchView.OnQueryTextListener implementation class, Loaders restart when the query conditions change, in order to get the latest results.

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;
}

How to use the callback method LoaderManager

LoaderManager.LoaderCallbacks interface is the client and LoaderManager interact belt.
Loader, particularly CursorLoader, expect to save their state in the stopped state. In this case, the user interaction process, avoiding reload the data which led to UI stuck situation. Use the callback function, you can know when to create a new Loader, and tells the application when to stop using Data Loader to load.

Callback method are:

  • onCreateLoader (): Creates a new Loader the given ID;
  • onLoaderFinished (): When the data loading is completed calls Loader;
  • onLoaderReset (): Loader reset data before voiding;
 
onCreateLoader Example:

// If non-null, this is the current filter the user has provided.

String mCurFilter;

...

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, pick 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");
}

CursorLoader (Context context, Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder) constructor of parameters:
the Context: Context, here Activity object or Fragment objects
Uri: the content retrieval address
Projection: to display column, pass null to query all the columns
Selection: query filters statement similar to the SQL WHERE, pass null, it represents a query for all
selectionArgs: query parameters, defined in the selection of replacement?
sortOrder: Sort by definition, similar to the SQL ORDER BY


Complete example

public static class CursorLoaderListFragment extends ListFragment

        implements OnQueryTextListener, LoaderManager.LoaderCallbacks<Cursor> {

 

    // This is the Adapter being used to display the list's data.

    SimpleCursorAdapter mAdapter;

 

    // If non-null, this is the current filter the user has provided.

    String mCurFilter;

 

    @Override public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(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 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[] { 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) {

        // Place an action bar item for searching.

        MenuItem item = menu.add("Search");

        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

        // 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 retrieve.

    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, pick 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);

    }
}










Reproduced in: https: //my.oschina.net/cjkall/blog/195770

Guess you like

Origin blog.csdn.net/weixin_34132768/article/details/91756387