You should also read

Try it out

This lesson shows you how to retrieve a list of contacts whose data matches all or part of a
search string, using the following techniques:

Match contact names

Retrieve a list of contacts by matching the search string to all or part of the contact
name data. The Contacts Provider allows multiple instances of the same name, so this
technique can return a list of matches.

Match a specific type of data, such as a phone number

Retrieve a list of contacts by matching the search string to a particular type of detail
data such as an email address. For example, this technique allows you to list all of the
contacts whose email address matches the search string.

Match any type of data

Retrieve a list of contacts by matching the search string to any type of detail data,
including name, phone number, street address, email address, and so forth. For example,
this technique allows you to accept any type of data for a search string and then list the
contacts for which the data matches the string.

Note: All the examples in this lesson use a
CursorLoader to retrieve data from the Contacts
Provider. A CursorLoader runs its query on a
thread that's separate from the UI thread. This ensures that the query doesn't slow down UI
response times and cause a poor user experience. For more information, see the Android
training class
Loading Data in the Background.

Request Permission to Read the Provider

To do any type of search of the Contacts Provider, your app must have
READ_CONTACTS permission.
To request this, add this
<uses-permission>
element to your manifest file as a child element of
<manifest>:

<uses-permission android:name="android.permission.READ_CONTACTS" />

Match a Contact by Name and List the Results

This technique tries to match a search string to the name of a contact or contacts in the
Contact Provider's ContactsContract.Contacts table. You usually want
to display the results in a ListView, to allow the user to choose among
the matched contacts.

Define ListView and item layouts

To display the search results in a ListView, you need a main layout file
that defines the entire UI including the ListView, and an item layout
file that defines one line of the ListView. For example, you could create
the main layout file res/layout/contacts_list_view.xml with
the following XML:

Note: This lesson doesn't describe the UI for getting a search string from the
user, because you may want to get the string indirectly. For example, you can give the user
an option to search for contacts whose name matches a string in an incoming text message.

The two layout files you've written define a user interface that shows a
ListView. The next step is to write code that uses this UI to display a
list of contacts.

Define a Fragment that displays the list of contacts

To display the list of contacts, start by defining a Fragment
that's loaded by an Activity. Using a
Fragment is a more flexible technique, because you can use
one Fragment to display the list and a second
Fragment to display the details for a contact that the user
chooses from the list. Using this approach, you can combine one of the techniques presented in
this lesson with one from the lesson
Retrieving Details for a Contact.

To help you write queries against the Contacts Provider, the Android framework provides a
contracts class called ContactsContract, which defines useful
constants and methods for accessing the provider. When you use this class, you don't have to
define your own constants for content URIs, table names, or columns. To use this class,
include the following statement:

Note: Since
Contacts.DISPLAY_NAME_PRIMARY requires Android 3.0 (API version 11) or later, setting your
app's minSdkVersion to 10 or below generates an Android Lint warning in
Android Studio. To turn off this warning, add the annotation
@SuppressLint("InlinedApi") before the definition of FROM_COLUMNS.

Initialize the Fragment

Initialize the Fragment. Add the empty, public constructor
required by the Android system, and inflate the Fragment object's
UI in the callback method onCreateView().
For example:

Set the selected contact listener

When you display the results of a search, you usually want to allow the user to select a
single contact for further processing. For example, when the user clicks a contact you can
display the contact's address on a map. To provide this feature, you first defined the current
Fragment as the click listener by specifying that the class
implements AdapterView.OnItemClickListener, as shown in the section
Define a Fragment that displays the list of contacts.

Define a projection

Define a constant that contains the columns you want to return from your query. Each item in
the ListView displays the contact's display name,
which contains the main form of the contact's name. In Android 3.0 (API version 11) and later,
the name of this column is
Contacts.DISPLAY_NAME_PRIMARY; in versions previous to that, its name is
Contacts.DISPLAY_NAME.

Define constants for the Cursor column indexes

To get data from an individual column in a Cursor, you need
the column's index within the Cursor. You can define constants
for the indexes of the Cursor columns, because the indexes are
the same as the order of the column names in your projection. For example:

Specify the selection criteria

To specify the data you want, create a combination of text expressions and variables
that tell the provider the data columns to search and the values to find.

For the text expression, define a constant that lists the search columns. Although this
expression can contain values as well, the preferred practice is to represent the values with
a "?" placeholder. During retrieval, the placeholder is replaced with values from an
array. Using "?" as a placeholder ensures that the search specification is generated by binding
rather than by SQL compilation. This practice eliminates the possibility of malicious SQL
injection. For example:

Initialize the loader

Since you're using a CursorLoader to retrieve data,
you must initialize the background thread and other variables that control asynchronous
retrieval. Do the initialization in
onActivityCreated(), which
is invoked immediately before the Fragment UI appears, as
shown in the following example:

Implement onCreateLoader()

In onCreateLoader(),
set up the search string pattern. To make a string into a pattern, insert "%"
(percent) characters to represent a sequence of zero or more characters, or "_" (underscore)
characters to represent a single character, or both. For example, the pattern "%Jefferson%"
would match both "Thomas Jefferson" and "Jefferson Davis".

Return a new CursorLoader from the method. For the content
URI, use Contacts.CONTENT_URI.
This URI refers to the entire table, as shown in the following example:

public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
// Put the result Cursor in the adapter for the ListView
mCursorAdapter.swapCursor(cursor);
}

The method onLoaderReset() is invoked when the loader framework detects that the
result Cursor contains stale data. Delete the
SimpleCursorAdapter reference to the existing
Cursor. If you don't, the loader framework will not
recycle the Cursor, which causes a memory leak. For example:

You now have the key pieces of an app that matches a search string to contact names and returns
the result in a ListView. The user can click a contact name to select it.
This triggers a listener, in which you can work further with the contact's data. For example,
you can retrieve the contact's details. To learn how to do this, continue with the next
lesson, Retrieving Details for a Contact.

The remaining sections in this lesson demonstrate other ways of finding contacts in the
Contacts Provider.

Match a Contact By a Specific Type of Data

This technique allows you to specify the type of data you want to match. Retrieving
by name is a specific example of this type of query, but you can also do it for any of the types
of detail data associated with a contact. For example, you can retrieve contacts that have a
specific postal code; in this case, the search string has to match data stored in a postal code
row.

To implement this type of retrieval, first implement the following code, as listed in
previous sections:

Request Permission to Read the Provider.

Define ListView and item layouts.

Define a Fragment that displays the list of contacts.

Define global variables.

Initialize the Fragment.

Set up the CursorAdapter for the ListView.

Set the selected contact listener.

Define constants for the Cursor column indexes.

Although you're retrieving data from a different table, the order of the columns in
the projection is the same, so you can use the same indexes for the Cursor.

Define the onItemClick() method.

Initialize the loader.

Implement onLoadFinished() and onLoaderReset().

The following steps show you the additional code you need to match a search string to
a particular type of detail data and display the results.

Choose the data type and table

To search for a particular type of detail data, you have to know the custom MIME type value
for the data type. Each data type has a unique MIME type
value defined by a constant CONTENT_ITEM_TYPE in the subclass of
ContactsContract.CommonDataKinds associated with the data type.
The subclasses have names that indicate their data type; for example, the subclass for email
data is ContactsContract.CommonDataKinds.Email, and the custom MIME
type for email data is defined by the constant
Email.CONTENT_ITEM_TYPE.

Use the ContactsContract.Data table for your search. All of the
constants you need for your projection, selection clause, and sort order are defined in or
inherited by this table.

Define a projection

To define a projection, choose one or more of the columns defined in
ContactsContract.Data or the classes from which it inherits. The
Contacts Provider does an implicit join between ContactsContract.Data
and other tables before it returns rows. For example:

Define search criteria

To search for a string within a particular type of data, construct a selection clause from
the following:

The name of the column that contains your search string. This name varies by data type,
so you need to find the subclass of
ContactsContract.CommonDataKinds that corresponds to the data type
and then choose the column name from that subclass. For example, to search for
email addresses, use the column
Email.ADDRESS.

The search string itself, represented as the "?" character in the selection clause.

The name of the column that contains the custom MIME type value. This name is always
Data.MIMETYPE.

The custom MIME type value for the data type. As described previously, this is the constant
CONTENT_ITEM_TYPE in the
ContactsContract.CommonDataKinds subclass. For example, the MIME
type value for email data is
Email.CONTENT_ITEM_TYPE. Enclose the value in single quotes by concatenating a
"'" (single quote) character to the start and end of the constant; otherwise,
the provider interprets the value as a variable name rather than as a string value.
You don't need to use a placeholder for this value, because you're using a constant
rather than a user-supplied value.

Implement onCreateLoader()

Now that you've specified the data you want and how to find it, define a query in your
implementation of onCreateLoader(). Return a new CursorLoader from this
method, using your projection, selection text expression, and selection array as
arguments. For a content URI, use
Data.CONTENT_URI. For example:

These code snippets are the basis of a simple reverse lookup based on a specific type of detail
data. This is the best technique to use if your app focuses on a particular type of data, such
as emails, and you want allow users to get the names associated with a piece of data.

Match a Contact By Any Type of Data

Retrieving a contact based on any type of data returns contacts if any of their data matches a
the search string, including name, email address, postal address, phone number, and so forth.
This results in a broad set of search results. For example, if the search string
is "Doe", then searching for any data type returns the contact "John Doe"; it also returns
contacts who live on "Doe Street".

To implement this type of retrieval, first implement the following code, as listed in
previous sections:

The following steps show you the additional code you need to match a search string to
any type of data and display the results.

Remove selection criteria

Don't define the SELECTION constants or the mSelectionArgs variable.
These aren't used in this type of retrieval.

Implement onCreateLoader()

Implement the onCreateLoader() method, returning a new CursorLoader.
You don't need to convert the search string into a pattern, because the Contacts Provider does
that automatically. Use
Contacts.CONTENT_FILTER_URI as the base URI, and append your search string to it by calling
Uri.withAppendedPath(). Using this URI
automatically triggers searching for any data type, as shown in the following example:

These code snippets are the basis of an app that does a broad search of the Contacts Provider.
The technique is useful for apps that want to implement functionality similar to the
People app's contact list screen.