Cursorloader Usage Summary of Android

Source: Internet
Author: User

The work is focused on the contact module, where the application queries the data in many places, using the Cursorloader tool, which greatly simplifies the complexity of the code. Android since 3.0 provides the loader mechanism, at that time Google's API is simply introduced not to give a usage, we have little attention. Later, due to the performance optimization under the heavy model, R & R's friends discovered that this thing was very powerful, and it began to notice this mighty tool. Cursorloader is a subclass of loader, which can be said to be an upgraded version of loader. This summary is based on loader, understand the principle of understanding the Cursorloader.

First of all, Google's official introduction to loader loader to activity and fragment available, loader can move the data to load, loader to monitor the data source changes and will be actively reported, when the configuration changes, The regenerated loader automatically connects to the cursor before the change, which avoids checking the database again. I'm adding that loader can automatically release a resource when the application doesn't use the query. These introductions are available from the official document Hill since android3.0. At that time based on these do not know how to use, see the framework side of the implementation or confused: how to use. Now it's like activity, we don't know how to start an activity in the framework how to manage activity but we can still use activity very well; for Cursorloader, We do not need to know the principles of the framework, as long as we take advantage of the interface provided by Google Loadermanager and register events for its interface loadermanager.loadercallbacks can achieve the functionality we need.

In fact, Cursorloader can be regarded as a very cow query tool, with the ability of general query, such as the above Google official introduction. We use the Loadermanager.loadercallbacks interface to provide query configuration at the appropriate time or to take advantage of the results returned by the query. Use good cursorloader to implement good Loadermanager.loadercallbacks interface. Look at what is available in this interface:

Public interface Loadercallbacks<d> {

Public loader<d> oncreateloader (int id, Bundle args);

public void onloadfinished (loader<d> Loader, D data);

public void Onloaderreset (loader<d> Loader);

}

The first method Oncreateloader is called when the loader is created, in order to provide query configuration, such as query address, query item, etc. This method is called when the loader is initialized to register the interface, and the common code is as follows:

Getloadermanager (). Initloader (0, NULL, this);

The first parameter is the current activity inside the loader ID, generally 0, the second parameter is generally null, the third is to implement the Loadermanager.loadercallbacks class, is generally the current activity. This code executes after executing the Oncreateloader, then goes to query, after the query completes executes onloadfinished, does the thing which you need to do. Typically, the second method uses query results, such as passing to a adapter for display. The third method Onloaderreset is changed in our configuration, using Restartloader (int, Bundle,loadermanager.loadercallbacks<d>) The loader method is called after reinitialization, and is generally used to release the result reference to the previous loader query. The use of loader only requires the removal of references before reinitialization, and no need to close the cursor to release resources when exiting activity.

The usage of loader here has been said, remember the use of the above three methods, in the appropriate place to initialize the loader, we can use loader to achieve our needs. Now talk about the relationship between loader and Cursorloader: Loader is the core, it has realized the basic function, asynctaskloader inherit from loader, the main task is to take the time-consuming operation from the main thread to strip out Cursorloader inherits from Asynctaskloader, is a concrete class of generic class, also is our most commonly used loader.

The advent of loader has brought great convenience to Android application development. In the performance optimization of data loading there is a distribution load, before loader, we need to implement the query in the Asyncqueryhandler class, in its Onquerycomplete callback method trigger subsequent queries. These need to customize an internal class, a bunch of code, get dizzy. %>_<% used to loader as long as the onloadfinished inside add some judgment can, very convenient.

 Public classListviewloader extends listactivity implements Loadermanager.loadercallbacks<Cursor> {    //The Adapter being used to display the list ' s dataSimplecursoradapter Madapter; //These is the Contacts rows that we'll retrieve    StaticFinal string[] PROJECTION =Newstring[] {contactscontract.data._id, ContactsContract.Data.DISPLAY_NAME}; //This is the select criteria    StaticFinal String SELECTION ="(("+ContactsContract.Data.DISPLAY_NAME+"notnull) and ("+ContactsContract.Data.DISPLAY_NAME+"! = "))"; @Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); //Create a progress bar to display while the list loadsProgressBar ProgressBar =NewProgressBar ( This); Progressbar.setlayoutparams (Newlayoutparams (layoutparams.wrap_content, Layoutparams.wrap_content, Gravity.center)); Progressbar.setindeterminate (true);        Getlistview (). Setemptyview (ProgressBar); //must add the progress bar to the root of the layoutViewGroup root =(ViewGroup) Findviewbyid (Android.        R.id.content);        Root.addview (ProgressBar); //for the cursor adapter, specify which columns go to which viewsstring[] Fromcolumns ={ContactsContract.Data.DISPLAY_NAME}; int[] Toviews = {Android. R.ID.TEXT1};//The TextView in Simple_list_item_1//Create An empty adapter we'll use to display the loaded data. //We pass NULL for the cursor and then update it in onloadfinished ()Madapter =NewSimplecursoradapter ( This, Android. R.layout.simple_list_item_1,NULL, Fromcolumns, Toviews,0);        Setlistadapter (Madapter); //Prepare the loader. Either re-connect with an existing one,//or start a new one.Getloadermanager (). Initloader (0,NULL, This); }    //called when a new Loader needs to be created     PublicLoader<cursor> Oncreateloader (intID, Bundle args) {        //Now Create and return a Cursorloader//creating a Cursor for the data being displayed.        return NewCursorloader ( This, ContactsContract.Data.CONTENT_URI, PROJECTION, SELECTION,NULL,NULL); }    //called when a previously created loader have finished loading     Public voidOnloadfinished (loader<cursor>loader, Cursor data) {        //Swap the new cursor in. (The framework would take care of closing the//Old cursor once we return.)madapter.swapcursor (data); }    //called when a previously created loader is reset, making the data unavailable     Public voidOnloaderreset (loader<cursor>loader) {        //This was called when the last Cursor provided to onloadfinished ()//Above is on to being closed. We need to make sure we is no//longer using it.Madapter.swapcursor (NULL); } @Override Public voidOnlistitemclick (ListView L, View V,intPositionLongID) {//Do something if a list item is clicked    }}

Cursorloader Usage Summary of Android

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.