Home > Articles

This chapter is from the book

This chapter is from the book

CursorLoader

The previous section discussed the low-level details of how to perform database operations in Android using SQLiteDatabase. However, it did not discuss the fact that databases on Android are stored on the file system, meaning that accessing a database from the main thread should be avoided in order to keep an app responsive for the user. Accessing a database from a non-UI thread typically involves some type of asynchronous mechanism, where a request for database access is made and the response to the request is delivered at some point in the future. Because views can be updated only from the UI thread, apps need to make calls to update views on the UI thread even though the results to a database query may be delivered on a different thread.

Android provides multiple tools for executing potentially long-running code off the UI thread while having results processed in the UI thread. One such tool is the loader framework. For accessing databases, there is a specialized component of the Loader called CursorLoader, which, in addition to managing a cursor’s lifecycle with regard to an activity lifecycle, also takes care of running queries in a background thread and presenting the results on the main thread, making it easy to update the display.

Creating a CursorLoader

There are multiple pieces to the CursorLoader API. A CursorLoader is a specialized member of Android’s loader framework specifically designed to handle cursors. In a typical implementation, a CursorLoader uses a ContentProvider to run a query against a database, then returns the cursor produced from the ContentProvider back to an activity or fragment.

In order to use a CursorLoader, an activity gets an instance of the LoaderManager. The LoaderManager manages all loaders for an activity or fragment, including a CursorLoader.

Once an activity or fragment has a reference to its LoaderManager, it tells the LoaderManager to initialize a loader by providing the LoaderManager with an object that implements the LoaderManager.LoaderCallbacks interface in the LoaderManager.initLoader() method. The LoaderManager.LoaderCallbacks interface contains the following methods:

  • Loader<T> onCreateLoader(int id, Bundle args)

  • void onLoadFinished(Loader<T>, T data)

  • void onLoaderReset(Loader<T> loader)

LoaderCallbacks.onCreate() is responsible for creating a new loader and returning it to the LoaderManager. To use a CursorLoader, LoaderCallbacks.onCreate()creates, initializes, and returns a CursorLoader object that contains the information necessary to run a query against a database (through a ContentProvider).

Listing 5.11 shows the implementation of the onCreateLoader() method returning a CursorLoader.

Listing 5.11 Implementing onCreateLoader()

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    Loader<Cursor> loader = null;
    switch (id) {
        case LOADER_ID_PEOPLE:
            loader = new CursorLoader(this,
                    PEOPLE_URI,
                    new String[] {"first_name", "last_name", "id"},
                    null,
                    null,
                    "id ASC");
            break;
    }

    return loader;
}

In Listing 5.11, the onCreateLoader() method first checks the ID it was passed to know which loader it needs to create. It then instantiates a new CursorLoader object and returns it to the caller.

The constructor of CursorLoader can take parameters that allow the CursorLoader to run a query against a database. The CursorLoader constructor called in Listing 5.11 takes the following parameters:

  • Content context: Provides the application context needed by the loader

  • Uri uri: Defines the table against which to run the query

  • String[] projection: Specifies the SELECT clause for the query

  • String selection: Specifies the WHERE clause which may contain “?” as placeholders

  • String[] selectionArgs: Defines the substitution variables for the selection placeholders

  • String sortOrder: Defines the ORDER BY clause for the query

The last four parameters, projection, selection, selectionArgs, and sortOrder, are similar to parameters passed to the SQLiteDatabase.query() discussed earlier in this chapter. In fact, they also do the same thing: define what columns to include in the result set, define which rows to include in the result set, and define how the result set should be sorted.

Once the data is loaded, Loader.Callbacks.onLoadFinished() is called, allowing the callback object to use the data in the cursor. Listing 5.12 shows a call to onLoadFinished().

Listing 5.12 Implementing onLoadFinished()

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
while(data.moveToNext()) {
    int index;

    index = data.getColumnIndexOrThrow("first_name");
    String firstName = data.getString(index);

    index = data.getColumnIndexOrThrow("last_name");
    String lastName = data.getString(index);

    index = data.getColumnIndexOrThrow("id");
    long id = data.getLong(index);

    //... do something with data
}

Notice how similar the code in Listing 5.12 is to the code in Listing 5.10 where a direct call to SQLiteDatabase.query() was made. The code to process the results of the query is nearly identical. Also, when using the LoaderManager, the activity does not need to worry about calling Cursor.close() or making the database query on a non-UI thread. That is all handled by the loader framework.

There is one other important point to note about onLoadFinished(). It is not only called when the initial data is loaded; it is also called when changes to the data are detected by the Android database. There is one line of code that needs to be added to the ContentProvider to trigger this, and that is discussed next chapter. However, having a single point in the code that receives query data and can update the display can be really convenient. This architecture allows activities to easily react to changes in data without the developer worrying about explicitly notifying the activities of changes to the data. The LoaderManager handles the lifecycle and knows when to requery and pass the data to the LoaderManager.Callbacks when it needs to.

There is one more method in the LoaderManager.Callbacks interface that needs to be implemented to use a CursorLoader: LoaderManager.Callbacks.onLoaderReset(Loader<T> loader). This method is called by the LoaderManager when a loader that was previously created is reset and its data should no longer be used. For a CursorLoader, this typically means that any references to the cursor that was provided by onLoadFinished() need to be discarded as they are no longer active. If a reference to the cursor is not persisted, the onLoadReset() method can be empty.

Starting a CursorLoader

Now that the mechanics of using a CursorLoader have been discussed, it is time to focus on how to start a data load operation with the LoaderManager. For most use cases, an activity or a fragment implements the LoaderManager.Callbacks interface since it makes sense for the activity/fragment to process the cursor result in order to update its display. To start the load, LoaderManager.initLoader() is called. This ensures that the loader is created, calling onCreateLoader(), loading the data, and making a call to onLoadFinished().

Both activities and fragments can get their LoaderManager object by calling getLoaderManager(). They can then start the load process by calling LoaderManager.initLoader(). LoaderManager.initLoader() takes the following parameters:

  • int id: The ID of the loader. This is the same ID that is passed to onCreateLoader() and can be used to identify a loader (see Listing 5.11).

  • Bundle args: Extra data that might be needed to create the loader. This is also passed to onCreateLoader() (see Listing 5.11). This value can be null.

  • LoaderManager.LoaderCallbacks callbacks: An object to handle the LoaderManager callbacks. This is typically the activity or fragment that is making the call to initLoader().

The call to initLoader() should happen early in an Android component’s lifecycle. For activities, initLoader() is usually called in onCreate(). Fragments should call initLoader() in onActivityCreated() (calling initLoader() in a fragment before its activity is created can cause problems).

Once initLoader() is called, the LoaderManager checks to see if there is already a loader associated with the ID passed to initLoader(). If there is no loader associated with the ID, LoaderManager makes a call to onCreateLoader() to get the loader and associate it with the ID. If there is currently a loader associated with the ID, initLoader() continues to use the preexisting loader object. If the caller is in the started state, and there is already a loader associated with the ID, and the associated loader has already loaded its data, then a call to onLoadFinished() is made directly from initLoader(). This usually happens only if there is a configuration change.

One detail to note about initLoader() is that it cannot be used to alter the query that was used to create the CursorLoader that gets associated with an ID. Once the loader is created (remember, the query is used to define the CursorLoader), it is reused only on subsequent calls to initLoader(). If an activity/fragment needs to alter the query that was used to create a CursorLoader with a given ID, it needs to make a call to restartLoader().

Restarting a CursorLoader

Unlike the call to LoaderManager.initLoader(), a call to LoaderManager.restartLoader() disassociates a loader with a given ID and allows it to be re-created. This results in onCreateLoader() being called again, allowing a new CursorLoader object to be made which can contain a different query for a given ID. LoaderManager.restartLoader() takes the same parameter list as initLoader() (int id, Bundle, args, LoaderManager.Callbacks, and callbacks) and discards the old loader. This makes restartLoader() useful for when the query of a CursorLoader needs to change. However, the restartLoader() method should not be used to simply handle activity/fragment lifecycle changes as they are already handled by the LoaderManager.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020