content-provider-creating.jd revision 50e990c64fa23ce94efa76b9e72df7f8ec3cee6a
1page.title=Creating a Content Provider
2@jd:body
3<div id="qv-wrapper">
4<div id="qv">
5
6
7<h2>In this document</h2>
8<ol>
9    <li>
10        <a href="#DataStorage">Designing Data Storage</a>
11    </li>
12    <li>
13        <a href="#ContentURI">Designing Content URIs</a>
14    </li>
15    <li>
16        <a href="#ContentProvider">Implementing the ContentProvider Class</a>
17        <ol>
18            <li>
19                <a href="#RequiredAccess">Required Methods</a>
20            </li>
21            <li>
22                <a href="#Query">Implementing the query() method</a>
23            </li>
24            <li>
25                <a href="#Insert">Implementing the insert() method</a>
26            </li>
27            <li>
28                <a href="#Delete">Implementing the delete() method</a>
29            </li>
30            <li>
31                <a href="#Update">Implementing the update() method</a>
32            </li>
33            <li>
34                <a href="#OnCreate">Implementing the onCreate() method</a>
35            </li>
36        </ol>
37    </li>
38    <li>
39        <a href="#MIMETypes">Implementing Content Provider MIME Types</a>
40        <ol>
41            <li>
42                <a href="#TableMIMETypes">MIME types for tables</a>
43            </li>
44            <li>
45                <a href="#FileMIMETypes">MIME types for files</a>
46            </li>
47        </ol>
48    </li>
49    <li>
50        <a href="#ContractClass">Implementing a Contract Class</a>
51    </li>
52    <li>
53        <a href="#Permissions">Implementing Content Provider Permissions</a>
54    </li>
55    <li>
56        <a href="#ProviderElement">The &lt;provider&gt; Element</a>
57    </li>
58    <li>
59        <a href="#Intents">Intents and Data Access</a>
60    </li>
61</ol>
62<h2>Key classes</h2>
63    <ol>
64        <li>
65            {@link android.content.ContentProvider}
66        </li>
67        <li>
68            {@link android.database.Cursor}
69        </li>
70        <li>
71            {@link android.net.Uri}
72        </li>
73    </ol>
74<h2>Related Samples</h2>
75    <ol>
76        <li>
77            <a
78                href="{@docRoot}resources/samples/NotePad/index.html">
79                Note Pad sample application
80            </a>
81        </li>
82    </ol>
83<h2>See also</h2>
84    <ol>
85        <li>
86            <a href="{@docRoot}guide/topics/providers/content-provider-basics.html">
87            Content Provider Basics</a>
88        </li>
89        <li>
90            <a href="{@docRoot}guide/topics/providers/calendar-provider.html">
91            Calendar Provider</a>
92        </li>
93    </ol>
94</div>
95</div>
96
97
98<p>
99    A content provider manages access to a central repository of data. You implement a
100    provider as one or more classes in an Android application, along with elements in
101    the manifest file. One of your classes implements a subclass
102    {@link android.content.ContentProvider}, which is the interface between your provider and
103    other applications. Although content providers are meant to make data available to other
104    applications, you may of course have activities in your application that allow the user
105    to query and modify the data managed by your provider.
106</p>
107<p>
108    The rest of this topic is a basic list of steps for building a content provider and a list
109    of APIs to use.
110</p>
111
112
113<!-- Before You Start Building -->
114<h2 id="BeforeYouStart">Before You Start Building</h2>
115<p>
116    Before you start building a provider, do the following:
117</p>
118<ol>
119    <li>
120        <strong>Decide if you need a content provider</strong>. You need to build a content
121        provider if you want to provide one or more of the following features:
122        <ul>
123            <li>You want to offer complex data or files to other applications.</li>
124            <li>You want to allow users to copy complex data from your app into other apps.</li>
125            <li>You want to provide custom search suggestions using the search framework.</li>
126        </ul>
127    <p>
128        You <em>don't</em> need a provider to use an SQLite database if the use is entirely within
129        your own application.
130    </p>
131    </li>
132    <li>
133        If you haven't done so already, read the topic
134        <a href="{@docRoot}guide/topics/providers/content-provider-basics.html">
135        Content Provider Basics</a> to learn more about providers.
136    </li>
137</ol>
138<p>
139    Next, follow these steps to build your provider:
140</p>
141<ol>
142    <li>
143        Design the raw storage for your data. A content provider offers data in two ways:
144        <dl>
145            <dt>
146                File data
147            </dt>
148            <dd>
149                Data that normally goes into files, such as
150                photos, audio, or videos. Store the files in your application's private
151                space. In response to a request for a file from another application, your
152                provider can offer a handle to the file.
153            </dd>
154            <dt>
155                &quot;Structured&quot; data
156            </dt>
157            <dd>
158                Data that normally goes into a database, array, or similar structure.
159                Store the data in a form that's compatible with tables of rows and columns. A row
160                represents an entity, such as a person or an item in inventory. A column represents
161                some data for the entity, such a person's name or an item's price. A common way to
162                store this type of data is in an SQLite database, but you can use any type of
163                persistent storage. To learn more about the storage types available in the
164                Android system, see the section <a href="#DataStorage">
165                Designing Data Storage</a>.
166            </dd>
167        </dl>
168    </li>
169    <li>
170        Define a concrete implementation of the {@link android.content.ContentProvider} class and
171        its required methods. This class is the interface between your data and the rest of the
172        Android system. For more information about this class, see the section
173        <a href="#ContentProvider">Implementing the ContentProvider Class</a>.
174    </li>
175    <li>
176        Define the provider's authority string, its content URIs, and column names. If you want
177        the provider's application to handle intents, also define intent actions, extras data,
178        and flags. Also define the permissions that you will require for applications that want
179        to access your data. You should consider defining all of these values as constants in a
180        separate contract class; later, you can expose this class to other developers. For more
181        information about content URIs, see the
182        section <a href="#ContentURI">Designing Content URIs</a>.
183        For more information about intents, see the
184        section <a href="#Intents">Intents and Data Access</a>.
185    </li>
186    <li>
187        Add other optional pieces, such as sample data or an implementation
188        of {@link android.content.AbstractThreadedSyncAdapter} that can synchronize data between
189        the provider and cloud-based data.
190    </li>
191</ol>
192
193
194<!-- Designing Data Storage -->
195<h2 id="DataStorage">Designing Data Storage</h2>
196<p>
197    A content provider is the interface to data saved in a structured format. Before you create
198    the interface, you must decide how to store the data. You can store the data in any form you
199    like, and then design the interface to read and write the data as necessary.
200</p>
201<p>
202    These are some of the data storage technologies that are available in Android:
203</p>
204<ul>
205    <li>
206        The Android system includes an SQLite database API that Android's own providers use
207        to store table-oriented data. The
208        {@link android.database.sqlite.SQLiteOpenHelper} class helps you create databases, and the
209        {@link android.database.sqlite.SQLiteDatabase} class is the base class for accessing
210        databases.
211        <p>
212            Remember that you don't have to use a database to implement your repository. A provider
213            appears externally as a set of tables, similar to a relational database, but this is
214            not a requirement for the provider's internal implementation.
215        </p>
216    </li>
217    <li>
218        For storing file data, Android has a variety of file-oriented APIs.
219        To learn more about file storage, read the topic
220        <a href="{@docRoot}guide/topics/data/data-storage.html">Data Storage</a>. If you're
221        designing a provider that offers media-related data such as music or videos, you can
222        have a provider that combines table data and files.
223    </li>
224    <li>
225        For working with network-based data, use classes in {@link java.net} and
226        {@link android.net}. You can also synchronize network-based data to a local data
227        store such as a database, and then offer the data as tables or files.
228        The <a href="{@docRoot}resources/samples/SampleSyncAdapter/index.html">
229        Sample Sync Adapter</a> sample application demonstrates this type of synchronization.
230    </li>
231</ul>
232<h3 id="DataDesign">
233    Data design considerations
234</h3>
235<p>
236    Here are some tips for designing your provider's data structure:
237</p>
238<ul>
239    <li>
240        Table data should always have a &quot;primary key&quot; column that the provider maintains
241        as a unique numeric value for each row. You can use this value to link the row to related
242        rows in other tables (using it as a &quot;foreign key&quot;). Although you can use any name
243        for this column, using {@link android.provider.BaseColumns#_ID BaseColumns._ID} is the best
244        choice, because linking the results of a provider query to a
245        {@link android.widget.ListView} requires one of the retrieved columns to have the name
246        <code>_ID</code>.
247    </li>
248    <li>
249        If you want to provide bitmap images or other very large pieces of file-oriented data, store
250        the data in a file and then provide it indirectly rather than storing it directly in a
251        table. If you do this, you need to tell users of your provider that they need to use a
252        {@link android.content.ContentResolver} file method to access the data.
253    </li>
254    <li>
255        Use the Binary Large OBject (BLOB) data type to store data that varies in size or has a
256        varying structure. For example, you can use a BLOB column to store a
257        <a href="http://code.google.com/p/protobuf">protocol buffer</a> or
258        <a href="http://www.json.org">JSON structure</a>.
259        <p>
260            You can also use a BLOB to implement a <em>schema-independent</em> table. In
261            this type of table, you define a primary key column, a MIME type column, and one or
262            more generic columns as BLOB. The meaning of the data in the BLOB columns is indicated
263            by the value in the MIME type column. This allows you to store different row types in
264            the same table. The Contacts Provider's &quot;data&quot; table
265            {@link android.provider.ContactsContract.Data} is an example of a schema-independent
266            table.
267        </p>
268    </li>
269</ul>
270<!-- Designing Content URIs -->
271<h2 id="ContentURI">Designing Content URIs</h2>
272<p>
273    A <strong>content URI</strong> is a URI that identifies data in a provider. Content URIs include
274    the symbolic name of the entire provider (its <strong>authority</strong>) and a
275    name that points to a table or file (a <strong>path</strong>). The optional id part points to
276    an individual row in a table. Every data access method of
277    {@link android.content.ContentProvider} has a content URI as an argument; this allows you to
278    determine the table, row, or file to access.
279</p>
280<p>
281    The basics of content URIs are described in the topic
282    <a href="{@docRoot}guide/topics/providers/content-provider-basics.html">
283    Content Provider Basics</a>.
284</p>
285<h3>Designing an authority</h3>
286<p>
287    A provider usually has a single authority, which serves as its Android-internal name. To
288    avoid conflicts with other providers, you should use Internet domain ownership (in reverse)
289    as the basis of your provider authority. Because this recommendation is also true for Android
290    package names, you can define your provider authority as an extension of the name
291    of the package containing the provider. For example, if your Android package name is
292    <code>com.example.&lt;appname&gt;</code>, you should give your provider the
293    authority <code>com.example.&lt;appname&gt;.provider</code>.
294</p>
295<h3>Designing a path structure</h3>
296<p>
297    Developers usually create content URIs from the authority by appending paths that point to
298    individual tables. For example, if you have two tables <em>table1</em> and
299    <em>table2</em>, you combine the authority from the previous example to yield the
300    content URIs
301    <code>com.example.&lt;appname&gt;.provider/table1</code> and
302    <code>com.example.&lt;appname&gt;.provider/table2</code>. Paths aren't
303    limited to a single segment, and there doesn't have to be a table for each level of the path.
304</p>
305<h3>Handling content URI IDs</h3>
306<p>
307    By convention, providers offer access to a single row in a table by accepting a content URI
308    with an ID value for the row at the end of the URI. Also by convention, providers match the
309    ID value to the table's <code>_ID</code> column, and perform the requested access against the
310    row that matches.
311</p>
312<p>
313    This convention facilitates a common design pattern for apps accessing a provider. The app
314    does a query against the provider and displays the resulting {@link android.database.Cursor}
315    in a {@link android.widget.ListView} using a {@link android.widget.CursorAdapter}.
316    The definition of {@link android.widget.CursorAdapter} requires one of the columns in the
317    {@link android.database.Cursor} to be <code>_ID</code>
318</p>
319<p>
320    The user then picks one of the displayed rows from the UI in order to look at or modify the
321    data. The app gets the corresponding row from the {@link android.database.Cursor} backing the
322    {@link android.widget.ListView}, gets the <code>_ID</code> value for this row, appends it to
323    the content URI, and sends the access request to the provider. The provider can then do the
324    query or modification against the exact row the user picked.
325</p>
326<h3>Content URI patterns</h3>
327<p>
328    To help you choose which action to take for an incoming content URI, the provider API includes
329    the convenience class {@link android.content.UriMatcher}, which maps content URI "patterns" to
330    integer values. You can use the integer values in a <code>switch</code> statement that
331    chooses the desired action for the content URI or URIs that match a particular pattern.
332</p>
333<p>
334    A content URI pattern matches content URIs using wildcard characters:
335</p>
336    <ul>
337        <li>
338            <strong><code>*</code>:</strong> Matches a string of any valid characters of any length.
339        </li>
340        <li>
341            <strong><code>#</code>:</strong> Matches a string of numeric characters of any length.
342        </li>
343    </ul>
344<p>
345    As an example of designing and coding content URI handling, consider a provider with the
346    authority <code>com.example.app.provider</code> that recognizes the following content URIs
347    pointing to tables:
348</p>
349<ul>
350    <li>
351        <code>content://com.example.app.provider/table1</code>: A table called <code>table1</code>.
352    </li>
353    <li>
354        <code>content://com.example.app.provider/table2/dataset1</code>: A table called
355        <code>dataset1</code>.
356    </li>
357    <li>
358        <code>content://com.example.app.provider/table2/dataset2</code>: A table called
359        <code>dataset2</code>.
360    </li>
361    <li>
362        <code>content://com.example.app.provider/table3</code>: A table called <code>table3</code>.
363    </li>
364</ul>
365<p>
366    The provider also recognizes these content URIs if they have a row ID appended to them, as
367    for example <code>content://com.example.app.provider/table3/1</code> for the row identified by
368    <code>1</code> in <code>table3</code>.
369</p>
370<p>
371    The following content URI patterns would be possible:
372</p>
373<dl>
374    <dt>
375        <code>content://com.example.app.provider/*</code>
376    </dt>
377    <dd>
378        Matches any content URI in the provider.
379    </dd>
380    <dt>
381        <code>content://com.example.app.provider/table2/*</code>:
382    </dt>
383    <dd>
384        Matches a content URI for the tables <code>dataset1</code>
385        and <code>dataset2</code>, but doesn't match content URIs for <code>table1</code> or
386        <code>table3</code>.
387    </dd>
388    <dt>
389        <code>content://com.example.app.provider/table3/#</code>: Matches a content URI
390        for single rows in <code>table3</code>, such as
391        <code>content://com.example.app.provider/table3/6</code> for the row identified by
392        <code>6</code>.
393    </dt>
394</dl>
395<p>
396    The following code snippet shows how the methods in {@link android.content.UriMatcher} work.
397    This code handles URIs for an entire table differently from URIs for a
398    single row, by using the content URI pattern
399    <code>content://&lt;authority&gt;/&lt;path&gt;</code> for tables, and
400    <code>content://&lt;authority&gt;/&lt;path&gt;/&lt;id&gt;</code> for single rows.
401</p>
402<p>
403    The method {@link android.content.UriMatcher#addURI(String, String, int) addURI()} maps an
404    authority and path to an integer value. The method android.content.UriMatcher#match(Uri)
405    match()} returns the integer value for a URI. A <code>switch</code> statement
406    chooses between querying the entire table, and querying for a single record:
407</p>
408<pre class="prettyprint">
409public class ExampleProvider extends ContentProvider {
410...
411    // Creates a UriMatcher object.
412    private static final UriMatcher sUriMatcher;
413...
414    /*
415     * The calls to addURI() go here, for all of the content URI patterns that the provider
416     * should recognize. For this snippet, only the calls for table 3 are shown.
417     */
418...
419    /*
420     * Sets the integer value for multiple rows in table 3 to 1. Notice that no wildcard is used
421     * in the path
422     */
423    sUriMatcher.addURI("com.example.app.provider", "table3", 1);
424
425    /*
426     * Sets the code for a single row to 2. In this case, the "#" wildcard is
427     * used. "content://com.example.app.provider/table3/3" matches, but
428     * "content://com.example.app.provider/table3 doesn't.
429     */
430    sUriMatcher.addURI("com.example.app.provider", "table3/#", 2);
431...
432    // Implements ContentProvider.query()
433    public Cursor query(
434        Uri uri,
435        String[] projection,
436        String selection,
437        String[] selectionArgs,
438        String sortOrder) {
439...
440        /*
441         * Choose the table to query and a sort order based on the code returned for the incoming
442         * URI. Here, too, only the statements for table 3 are shown.
443         */
444        switch (sUriMatcher.match(uri)) {
445
446
447            // If the incoming URI was for all of table3
448            case 1:
449
450                if (TextUtils.isEmpty(sortOrder)) sortOrder = "_ID ASC";
451                break;
452
453            // If the incoming URI was for a single row
454            case 2:
455
456                /*
457                 * Because this URI was for a single row, the _ID value part is
458                 * present. Get the last path segment from the URI; this is the _ID value.
459                 * Then, append the value to the WHERE clause for the query
460                 */
461                selection = selection + "_ID = " uri.getLastPathSegment();
462                break;
463
464            default:
465            ...
466                // If the URI is not recognized, you should do some error handling here.
467        }
468        // call the code to actually do the query
469    }
470</pre>
471<p>
472    Another class, {@link android.content.ContentUris}, provides convenience methods for working
473    with the <code>id</code> part of content URIs. The classes {@link android.net.Uri} and
474    {@link android.net.Uri.Builder} include convenience methods for parsing existing
475    {@link android.net.Uri} objects and building new ones.
476</p>
477
478<!-- Implementing the ContentProvider class -->
479<h2 id="ContentProvider">Implementing the ContentProvider Class</h2>
480<p>
481    The {@link android.content.ContentProvider} instance manages access
482    to a structured set of data by handling requests from other applications. All forms
483    of access eventually call {@link android.content.ContentResolver}, which then calls a concrete
484    method of {@link android.content.ContentProvider} to get access.
485</p>
486<h3 id="RequiredAccess">Required methods</h3>
487<p>
488    The abstract class {@link android.content.ContentProvider} defines six abstract methods that
489    you must implement as part of your own concrete subclass. All of these methods except
490    {@link android.content.ContentProvider#onCreate() onCreate()} are called by a client application
491    that is attempting to access your content provider:
492</p>
493<dl>
494    <dt>
495        {@link android.content.ContentProvider#query(Uri, String[], String, String[], String)
496        query()}
497    </dt>
498    <dd>
499        Retrieve data from your provider. Use the arguments to select the table to
500        query, the rows and columns to return, and the sort order of the result.
501        Return the data as a {@link android.database.Cursor} object.
502    </dd>
503    <dt>
504        {@link android.content.ContentProvider#insert(Uri, ContentValues) insert()}
505    </dt>
506    <dd>
507        Insert a new row into your provider. Use the arguments to select the
508        destination table and to get the column values to use. Return a content URI for the
509        newly-inserted row.
510    </dd>
511    <dt>
512        {@link android.content.ContentProvider#update(Uri, ContentValues, String, String[])
513        update()}
514    </dt>
515    <dd>
516        Update existing rows in your provider. Use the arguments to select the table and rows
517        to update and to get the updated column values. Return the number of rows updated.
518    </dd>
519    <dt>
520        {@link android.content.ContentProvider#delete(Uri, String, String[]) delete()}
521    </dt>
522    <dd>
523        Delete rows from your provider. Use the arguments to select the table and the rows to
524        delete. Return the number of rows deleted.
525    </dd>
526    <dt>
527        {@link android.content.ContentProvider#getType(Uri) getType()}
528    </dt>
529    <dd>
530        Return the MIME type corresponding to a content URI. This method is described in more
531        detail in the section <a href="#MIMETypes">Implementing Content Provider MIME Types</a>.
532    </dd>
533    <dt>
534        {@link android.content.ContentProvider#onCreate() onCreate()}
535    </dt>
536    <dd>
537        Initialize your provider. The Android system calls this method immediately after it
538        creates your provider. Notice that your provider is not created until a
539        {@link android.content.ContentResolver} object tries to access it.
540    </dd>
541</dl>
542<p>
543    Notice that these methods have the same signature as the identically-named
544    {@link android.content.ContentResolver} methods.
545</p>
546<p>
547    Your implementation of these methods should account for the following:
548</p>
549<ul>
550    <li>
551        All of these methods except {@link android.content.ContentProvider#onCreate() onCreate()}
552        can be called by multiple threads at once, so they must be thread-safe. To learn
553        more about multiple threads, see the topic
554        <a href="{@docRoot}guide/components/processes-and-threads.html">
555        Processes and Threads</a>.
556    </li>
557    <li>
558        Avoid doing lengthy operations in {@link android.content.ContentProvider#onCreate()
559        onCreate()}. Defer initialization tasks until they are actually needed.
560        The section <a href="#OnCreate">Implementing the onCreate() method</a>
561        discusses this in more detail.
562    </li>
563    <li>
564        Although you must implement these methods, your code does not have to do anything except
565        return the expected data type. For example, you may want to prevent other applications
566        from inserting data into some tables. To do this, you can ignore the call to
567        {@link android.content.ContentProvider#insert(Uri, ContentValues) insert()} and return
568        0.
569    </li>
570</ul>
571<h3 id="Query">Implementing the query() method</h3>
572<p>
573    The
574    {@link android.content.ContentProvider#query(Uri, String[], String, String[], String)
575    ContentProvider.query()} method must return a {@link android.database.Cursor} object, or if it
576    fails, throw an {@link java.lang.Exception}. If you are using an SQLite database as your data
577    storage, you can simply return the {@link android.database.Cursor} returned by one of the
578    <code>query()</code> methods of the {@link android.database.sqlite.SQLiteDatabase} class.
579    If the query does not match any rows, you should return a {@link android.database.Cursor}
580    instance whose {@link android.database.Cursor#getCount()} method returns 0.
581    You should return <code>null</code> only if an internal error occurred during the query process.
582</p>
583<p>
584    If you aren't using an SQLite database as your data storage, use one of the concrete subclasses
585    of {@link android.database.Cursor}. For example, the {@link android.database.MatrixCursor} class
586    implements a cursor in which each row is an array of {@link java.lang.Object}. With this class,
587    use {@link android.database.MatrixCursor#addRow(Object[]) addRow()} to add a new row.
588</p>
589<p>
590    Remember that the Android system must be able to communicate the {@link java.lang.Exception}
591    across process boundaries. Android can do this for the following exceptions that may be useful
592    in handling query errors:
593</p>
594<ul>
595    <li>
596        {@link java.lang.IllegalArgumentException} (You may choose to throw this if your provider
597        receives an invalid content URI)
598    </li>
599    <li>
600        {@link java.lang.NullPointerException}
601    </li>
602</ul>
603<h3 id="Insert">Implementing the insert() method</h3>
604<p>
605    The {@link android.content.ContentProvider#insert(Uri, ContentValues) insert()} method adds a
606    new row to the appropriate table, using the values in the {@link android.content.ContentValues}
607    argument. If a column name is not in the {@link android.content.ContentValues} argument, you
608    may want to provide a default value for it either in your provider code or in your database
609    schema.
610</p>
611<p>
612    This method should return the content URI for the new row. To construct this, append the new
613    row's <code>_ID</code> (or other primary key) value to the table's content URI, using
614    {@link android.content.ContentUris#withAppendedId(Uri, long) withAppendedId()}.
615</p>
616<h3 id="Delete">Implementing the delete() method</h3>
617<p>
618    The {@link android.content.ContentProvider#delete(Uri, String, String[]) delete()} method
619    does not have to physically delete rows from your data storage. If you are using a sync adapter
620    with your provider, you should consider marking a deleted row
621    with a &quot;delete&quot; flag rather than removing the row entirely. The sync adapter can
622    check for deleted rows and remove them from the server before deleting them from the provider.
623</p>
624<h3 id="Update">Implementing the update() method</h3>
625<p>
626    The {@link android.content.ContentProvider#update(Uri, ContentValues, String, String[])
627    update()} method takes the same {@link android.content.ContentValues} argument used by
628    {@link android.content.ContentProvider#insert(Uri, ContentValues) insert()}, and the
629    same <code>selection</code> and <code>selectionArgs</code> arguments used by
630    {@link android.content.ContentProvider#delete(Uri, String, String[]) delete()} and
631    {@link android.content.ContentProvider#query(Uri, String[], String, String[], String)
632    ContentProvider.query()}. This may allow you to re-use code between these methods.
633</p>
634<h3 id="OnCreate">Implementing the onCreate() method</h3>
635<p>
636    The Android system calls {@link android.content.ContentProvider#onCreate()
637    onCreate()} when it starts up the provider. You should perform only fast-running initialization
638    tasks in this method, and defer database creation and data loading until the provider actually
639    receives a request for the data. If you do lengthy tasks in
640    {@link android.content.ContentProvider#onCreate() onCreate()}, you will slow down your
641    provider's startup. In turn, this will slow down the response from the provider to other
642    applications.
643</p>
644<p>
645    For example, if you are using an SQLite database you can create
646    a new {@link android.database.sqlite.SQLiteOpenHelper} object in
647    {@link android.content.ContentProvider#onCreate() ContentProvider.onCreate()},
648    and then create the SQL tables the first time you open the database. To facilitate this, the
649    first time you call {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase
650    getWritableDatabase()}, it automatically calls the
651    {@link android.database.sqlite.SQLiteOpenHelper#onCreate(SQLiteDatabase)
652    SQLiteOpenHelper.onCreate()} method.
653</p>
654<p>
655    The following two snippets demonstrate the interaction between
656    {@link android.content.ContentProvider#onCreate() ContentProvider.onCreate()} and
657    {@link android.database.sqlite.SQLiteOpenHelper#onCreate(SQLiteDatabase)
658    SQLiteOpenHelper.onCreate()}. The first snippet is the implementation of
659    {@link android.content.ContentProvider#onCreate() ContentProvider.onCreate()}:
660</p>
661<pre class="prettyprint">
662public class ExampleProvider extends ContentProvider
663
664    /*
665     * Defines a handle to the database helper object. The MainDatabaseHelper class is defined
666     * in a following snippet.
667     */
668    private MainDatabaseHelper mOpenHelper;
669
670    // Defines the database name
671    private static final String DBNAME = "mydb";
672
673    // Holds the database object
674    private SQLiteDatabase db;
675
676    public boolean onCreate() {
677
678        /*
679         * Creates a new helper object. This method always returns quickly.
680         * Notice that the database itself isn't created or opened
681         * until SQLiteOpenHelper.getWritableDatabase is called
682         */
683        mOpenHelper = new SQLiteOpenHelper(
684            getContext(),        // the application context
685            DBNAME,              // the name of the database)
686            null,                // uses the default SQLite cursor
687            1                    // the version number
688        );
689
690        return true;
691    }
692
693    ...
694
695    // Implements the provider's insert method
696    public Cursor insert(Uri uri, ContentValues values) {
697        // Insert code here to determine which table to open, handle error-checking, and so forth
698
699        ...
700
701        /*
702         * Gets a writeable database. This will trigger its creation if it doesn't already exist.
703         *
704         */
705        db = mOpenHelper.getWritableDatabase();
706    }
707}
708</pre>
709<p>
710    The next snippet is the implementation of
711    {@link android.database.sqlite.SQLiteOpenHelper#onCreate(SQLiteDatabase)
712    SQLiteOpenHelper.onCreate()}, including a helper class:
713</p>
714<pre class="prettyprint">
715...
716// A string that defines the SQL statement for creating a table
717private static final String SQL_CREATE_MAIN = "CREATE TABLE " +
718    "main " +                       // Table's name
719    "(" +                           // The columns in the table
720    " _ID INTEGER PRIMARY KEY, " +
721    " WORD TEXT"
722    " FREQUENCY INTEGER " +
723    " LOCALE TEXT )";
724...
725/**
726 * Helper class that actually creates and manages the provider's underlying data repository.
727 */
728protected static final class MainDatabaseHelper extends SQLiteOpenHelper {
729
730    /*
731     * Instantiates an open helper for the provider's SQLite data repository
732     * Do not do database creation and upgrade here.
733     */
734    MainDatabaseHelper(Context context) {
735        super(context, DBNAME, null, 1);
736    }
737
738    /*
739     * Creates the data repository. This is called when the provider attempts to open the
740     * repository and SQLite reports that it doesn't exist.
741     */
742    public void onCreate(SQLiteDatabase db) {
743
744        // Creates the main table
745        db.execSQL(SQL_CREATE_MAIN);
746    }
747}
748</pre>
749
750
751<!-- Implementing ContentProvider MIME Types -->
752<h2 id="MIMETypes">Implementing ContentProvider MIME Types</h2>
753<p>
754    The {@link android.content.ContentProvider} class has two methods for returning MIME types:
755</p>
756<dl>
757    <dt>
758        {@link android.content.ContentProvider#getType(Uri) getType()}
759    </dt>
760    <dd>
761        One of the required methods that you must implement for any provider.
762    </dd>
763    <dt>
764        {@link android.content.ContentProvider#getStreamTypes(Uri, String) getStreamTypes()}
765    </dt>
766    <dd>
767        A method that you're expected to implement if your provider offers files.
768    </dd>
769</dl>
770<h3 id="TableMIMETypes">MIME types for tables</h3>
771<p>
772    The {@link android.content.ContentProvider#getType(Uri) getType()} method returns a
773    {@link java.lang.String} in MIME format that describes the type of data returned by the content
774    URI argument. The {@link android.net.Uri} argument can be a pattern rather than a specific URI;
775    in this case, you should return the type of data associated with content URIs that match the
776    pattern.
777</p>
778<p>
779    For common types of data such as as text, HTML, or JPEG,
780    {@link android.content.ContentProvider#getType(Uri) getType()} should return the standard
781    MIME type for that data. A full list of these standard types is available on the
782    <a href="http://www.iana.org/assignments/media-types/index.htm">IANA MIME Media Types</a>
783    website.
784</p>
785<p>
786    For content URIs that point to a row or rows of table data,
787    {@link android.content.ContentProvider#getType(Uri) getType()} should return
788    a MIME type in Android's vendor-specific MIME format:
789</p>
790<ul>
791    <li>
792        Type part: <code>vnd</code>
793    </li>
794    <li>
795        Subtype part:
796        <ul>
797            <li>
798    If the URI pattern is for a single row: <code>android.cursor.<strong>item</strong>/</code>
799            </li>
800            <li>
801    If the URI pattern is for more than one row: <code>android.cursor.<strong>dir</strong>/</code>
802            </li>
803        </ul>
804    </li>
805    <li>
806        Provider-specific part: <code>vnd.&lt;name&gt;</code>.<code>&lt;type&gt;</code>
807        <p>
808            You supply the <code>&lt;name&gt;</code> and <code>&lt;type&gt;</code>.
809            The <code>&lt;name&gt;</code> value should be globally unique,
810            and the <code>&lt;type&gt;</code> value should be unique to the corresponding URI
811            pattern. A good choice for <code>&lt;name&gt;</code> is your company's name or
812            some part of your application's Android package name. A good choice for the
813            <code>&lt;type&gt;</code> is a string that identifies the table associated with the
814            URI.
815        </p>
816
817    </li>
818</ul>
819<p>
820    For example, if a provider's authority is
821    <code>com.example.app.provider</code>, and it exposes a table named
822    <code>table1</code>, the MIME type for multiple rows in <code>table1</code> is:
823</p>
824<pre>
825vnd.android.cursor.<strong>dir</strong>/vnd.com.example.provider.table1
826</pre>
827<p>
828    For a single row of <code>table1</code>, the MIME type is:
829</p>
830<pre>
831vnd.android.cursor.<strong>item</strong>/vnd.com.example.provider.table1
832</pre>
833<h3 id="FileMIMETypes">MIME types for files</h3>
834<p>
835    If your provider offers files, implement
836    {@link android.content.ContentProvider#getStreamTypes(Uri, String) getStreamTypes()}.
837    The method returns a {@link java.lang.String} array of MIME types for the files your provider
838    can return for a given content URI. You should filter the MIME types you offer by the MIME type
839    filter argument, so that you return only those MIME types that the client wants to handle.
840</p>
841<p>
842    For example, consider a provider that offers photo images as files in <code>.jpg</code>,
843    <code>.png</code>, and <code>.gif</code> format.
844    If an application calls {@link android.content.ContentResolver#getStreamTypes(Uri, String)
845    ContentResolver.getStreamTypes()} with the filter string <code>image/*</code> (something that
846    is an &quot;image&quot;),
847    then the {@link android.content.ContentProvider#getStreamTypes(Uri, String)
848    ContentProvider.getStreamTypes()} method should return the array:
849</p>
850<pre>
851{ &quot;image/jpeg&quot;, &quot;image/png&quot;, &quot;image/gif&quot;}
852</pre>
853<p>
854    If the app is only interested in <code>.jpg</code> files, then it can call
855    {@link android.content.ContentResolver#getStreamTypes(Uri, String)
856    ContentResolver.getStreamTypes()} with the filter string <code>*\/jpeg</code>, and
857    {@link android.content.ContentProvider#getStreamTypes(Uri, String)
858    ContentProvider.getStreamTypes()} should return:
859<pre>
860{&quot;image/jpeg&quot;}
861</pre>
862<p>
863    If your provider doesn't offer any of the MIME types requested in the filter string,
864    {@link android.content.ContentProvider#getStreamTypes(Uri, String) getStreamTypes()}
865    should return <code>null</code>.
866</p>
867
868
869<!--  Implementing a Contract Class -->
870<h2 id="ContractClass">Implementing a Contract Class</h2>
871<p>
872    A contract class is a <code>public final</code> class that contains constant definitions for the
873    URIs, column names, MIME types, and other meta-data that pertain to the provider. The class
874    establishes a contract between the provider and other applications by ensuring that the provider
875    can be correctly accessed even if there are changes to the actual values of URIs, column names,
876    and so forth.
877</p>
878<p>
879    A contract class also helps developers because it usually has mnemonic names for its constants,
880    so developers are less likely to use incorrect values for column names or URIs. Since it's a
881    class, it can contain Javadoc documentation. Integrated development environments such as
882    Eclipse can auto-complete constant names from the contract class and display Javadoc for the
883    constants.
884</p>
885<p>
886    Developers can't access the contract class's class file from your application, but they can
887    statically compile it into their application from a <code>.jar</code> file you provide.
888</p>
889<p>
890    The {@link android.provider.ContactsContract} class and its nested classes are examples of
891    contract classes.
892</p>
893<h2 id="Permissions">Implementing Content Provider Permissions</h2>
894<p>
895    Permissions and access for all aspects of the Android system are described in detail in the
896    topic <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>.
897    The topic <a href="{@docRoot}guide/topics/data/data-storage.html">Data Storage</a> also
898    described the security and permissions in effect for various types of storage.
899    In brief, the important points are:
900</p>
901<ul>
902    <li>
903        By default, data files stored on the device's internal storage are private to your
904        application and provider.
905    </li>
906    <li>
907        {@link android.database.sqlite.SQLiteDatabase} databases you create are private to your
908        application and provider.
909    </li>
910    <li>
911        By default, data files that you save to external storage are <em>public</em> and
912        <em>world-readable</em>. You can't use a content provider to restrict access to files in
913        external storage, because other applications can use other API calls to read and write them.
914    </li>
915    <li>
916        The method calls for opening or creating files or SQLite databases on your device's internal
917        storage can potentially give both read and write access to all other applications. If you
918        use an internal file or database as your provider's repository, and you give it
919        "world-readable" or "world-writeable" access, the permissions you set for your provider in
920        its manifest won't protect your data. The default access for files and databases in
921        internal storage is "private", and for your provider's repository you shouldn't change this.
922    </li>
923</ul>
924<p>
925    If you want to use content provider permissions to control access to your data, then you should
926    store your data in internal files, SQLite databases, or the &quot;cloud&quot; (for example,
927    on a remote server), and you should keep files and databases private to your application.
928</p>
929<h3>Implementing permissions</h3>
930<p>
931    All applications can read from or write to your provider, even if the underlying data is
932    private, because by default your provider does not have permissions set. To change this,
933    set permissions for your provider in your manifest file, using attributes or child
934    elements of the <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">
935    &lt;provider&gt;</a></code> element. You can set permissions that apply to the entire provider,
936    or to certain tables, or even to certain records, or all three.
937</p>
938<p>
939    You define permissions for your provider with one or more
940    <code><a href="{@docRoot}guide/topics/manifest/permission-element.html">
941    &lt;permission&gt;</a></code> elements in your manifest file. To make the
942    permission unique to your provider, use Java-style scoping for the
943    <code><a href="{@docRoot}guide/topics/manifest/permission-element.html#nm">
944    android:name</a></code> attribute. For example, name the read permission
945    <code>com.example.app.provider.permission.READ_PROVIDER</code>.
946
947</p>
948<p>
949    The following list describes the scope of provider permissions, starting with the
950    permissions that apply to the entire provider and then becoming more fine-grained.
951    More fine-grained permissions take precedence over ones with larger scope:
952</p>
953<dl>
954    <dt>
955        Single read-write provider-level permission
956    </dt>
957    <dd>
958        One permission that controls both read and write access to the entire provider, specified
959        with the <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#prmsn">
960        android:permission</a></code> attribute of the
961        <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">
962        &lt;provider&gt;</a></code> element.
963    </dd>
964    <dt>
965        Separate read and write provider-level permission
966    </dt>
967    <dd>
968        A read permission and a write permission for the entire provider. You specify them
969        with the <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#rprmsn">
970        android:readPermission</a></code> and
971        <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#wprmsn">
972        android:writePermission</a></code> attributes of the
973        <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">
974        &lt;provider&gt;</a></code> element. They take precedence over the permission required by
975        <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#prmsn">
976        android:permission</a></code>.
977    </dd>
978    <dt>
979        Path-level permission
980    </dt>
981    <dd>
982        Read, write, or read/write permission for a content URI in your provider. You specify
983        each URI you want to control with a
984        <code><a href="{@docRoot}guide/topics/manifest/path-permission-element.html">
985        &lt;path-permission&gt;</a></code> child element of the
986        <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">
987        &lt;provider&gt;</a></code> element. For each content URI you specify, you can specify a
988        read/write permission, a read permission, or a write permission, or all three. The read and
989        write permissions take precedence over the read/write permission. Also, path-level
990        permission takes precedence over provider-level permissions.
991    </dd>
992    <dt>
993        Temporary permission
994    </dt>
995    <dd>
996        A permission level that grants temporary access to an application, even if the application
997        doesn't have the permissions that are normally required. The temporary
998        access feature reduces the number of permissions an application has to request in
999        its manifest. When you turn on temporary permissions, the only applications that need
1000        &quot;permanent&quot; permissions for your provider are ones that continually access all
1001        your data.
1002        <p>
1003            Consider the permissions you need to implement an email provider and app, when you
1004            want to allow an outside image viewer application to display photo attachments from your
1005            provider. To give the image viewer the necessary access without requiring permissions,
1006            set up temporary permissions for content URIs for photos. Design your email app so
1007            that when the user wants to display a photo, the app sends an intent containing the
1008            photo's content URI and permission flags to the image viewer. The image viewer can
1009            then query your email provider to retrieve the photo, even though the viewer doesn't
1010            have the normal read permission for your provider.
1011        </p>
1012        <p>
1013            To turn on temporary permissions, either set the
1014            <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn">
1015            android:grantUriPermissions</a></code> attribute of the
1016            <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">
1017            &lt;provider&gt;</a></code> element, or add one or more
1018            <code><a href="{@docRoot}guide/topics/manifest/grant-uri-permission-element.html">
1019            &lt;grant-uri-permission&gt;</a></code> child elements to your
1020            <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">
1021            &lt;provider&gt;</a></code> element. If you use temporary permissions, you have to call
1022            {@link android.content.Context#revokeUriPermission(Uri, int)
1023            Context.revokeUriPermission()} whenever you remove support for a content URI from your
1024            provider, and the content URI is associated with a temporary permission.
1025        </p>
1026        <p>
1027            The attribute's value determines how much of your provider is made accessible.
1028            If the attribute is set to <code>true</code>, then the system will grant temporary
1029            permission to your entire provider, overriding any other permissions that are required
1030            by your provider-level or path-level permissions.
1031        </p>
1032        <p>
1033            If this flag is set to <code>false</code>, then you must add
1034            <code><a href="{@docRoot}guide/topics/manifest/grant-uri-permission-element.html">
1035            &lt;grant-uri-permission&gt;</a></code> child elements to your
1036            <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">
1037            &lt;provider&gt;</a></code> element. Each child element specifies the content URI or
1038            URIs for which temporary access is granted.
1039        </p>
1040        <p>
1041            To delegate temporary access to an application, an intent must contain
1042            the {@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION} or the
1043            {@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION} flags, or both. These
1044            are set with the {@link android.content.Intent#setFlags(int) setFlags()} method.
1045        </p>
1046        <p>
1047            If the <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn">
1048            android:grantUriPermissions</a></code> attribute is not present, it's assumed to be
1049            <code>false</code>.
1050        </p>
1051    </dd>
1052</dl>
1053
1054
1055
1056<!-- The Provider Element -->
1057<h2 id="ProviderElement">The &lt;provider&gt; Element</h2>
1058<p>
1059    Like {@link android.app.Activity} and {@link android.app.Service} components,
1060    a subclass of {@link android.content.ContentProvider}
1061    must be defined in the manifest file for its application, using the
1062    <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">
1063    &lt;provider&gt;</a></code> element. The Android system gets the following information from
1064    the element:
1065<dl>
1066    <dt>
1067        Authority
1068        (<a href="{@docRoot}guide/topics/manifest/provider-element.html#auth">{@code
1069        android:authorities}</a>)
1070    </dt>
1071    <dd>
1072        Symbolic names that identify the entire provider within the system. This
1073        attribute is described in more detail in the section
1074        <a href="#ContentURI">Designing Content URIs</a>.
1075    </dd>
1076    <dt>
1077        Provider class name
1078        (<code>
1079<a href="{@docRoot}guide/topics/manifest/provider-element.html#nm">android:name</a>
1080        </code>)
1081    </dt>
1082    <dd>
1083        The class that implements {@link android.content.ContentProvider}. This class is
1084        described in more detail in the section
1085        <a href="#ContentProvider">Implementing the ContentProvider Class</a>.
1086    </dd>
1087    <dt>
1088        Permissions
1089    </dt>
1090    <dd>
1091        Attributes that specify the permissions that other applications must have in order to access
1092        the provider's data:
1093        <ul>
1094            <li>
1095                <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn">
1096                android:grantUriPermssions</a></code>: Temporary permission flag.
1097            </li>
1098            <li>
1099                <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#prmsn">
1100                android:permission</a></code>: Single provider-wide read/write permission.
1101            </li>
1102            <li>
1103                <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#rprmsn">
1104                android:readPermission</a></code>: Provider-wide read permission.
1105            </li>
1106            <li>
1107                <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#wprmsn">
1108                android:writePermission</a></code>: Provider-wide write permission.
1109            </li>
1110        </ul>
1111        <p>
1112            Permissions and their corresponding attributes are described in more
1113            detail in the section
1114            <a href="#Permissions">Implementing Content Provider Permissions</a>.
1115        </p>
1116    </dd>
1117    <dt>
1118        Startup and control attributes
1119    </dt>
1120    <dd>
1121        These attributes determine how and when the Android system starts the provider, the
1122        process characteristics of the provider, and other run-time settings:
1123        <ul>
1124            <li>
1125                <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#enabled">
1126                android:enabled</a></code>: Flag allowing the system to start the provider.
1127            </li>
1128              <li>
1129                <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#exported">
1130                android:exported</a></code>: Flag allowing other applications to use this provider.
1131            </li>
1132            <li>
1133                <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#init">
1134                android:initOrder</a></code>: The order in which this provider should be started,
1135                relative to other providers in the same process.
1136            </li>
1137            <li>
1138                <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#multi">
1139                android:multiProcess</a></code>: Flag allowing the system to start the provider
1140                in the same process as the calling client.
1141            </li>
1142            <li>
1143                <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#proc">
1144                android:process</a></code>: The name of the process in which the provider should
1145                run.
1146            </li>
1147            <li>
1148                <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#sync">
1149                android:syncable</a></code>: Flag indicating that the provider's data is to be
1150                sync'ed with data on a server.
1151            </li>
1152        </ul>
1153        <p>
1154            The attributes are fully documented in the dev guide topic for the
1155            <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">
1156            &lt;provider&gt;</a></code>
1157            element.
1158        </p>
1159    </dd>
1160    <dt>
1161        Informational attributes
1162    </dt>
1163    <dd>
1164        An optional icon and label for the provider:
1165        <ul>
1166            <li>
1167                <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#icon">
1168                android:icon</a></code>: A drawable resource containing an icon for the provider.
1169                The icon appears next to the provider's label in the list of apps in
1170                <em>Settings</em> &gt; <em>Apps</em> &gt; <em>All</em>.
1171            </li>
1172            <li>
1173                <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#label">
1174                android:label</a></code>: An informational label describing the provider or its
1175                data, or both. The label appears in the list of apps in
1176                <em>Settings</em> &gt; <em>Apps</em> &gt; <em>All</em>.
1177            </li>
1178        </ul>
1179        <p>
1180            The attributes are fully documented in the dev guide topic for the
1181            <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">
1182            &lt;provider&gt;</a></code> element.
1183        </p>
1184    </dd>
1185</dl>
1186
1187<!-- Intent Access -->
1188<h2 id="Intents">Intents and Data Access</h2>
1189<p>
1190    Applications can access a content provider indirectly with an {@link android.content.Intent}.
1191    The application does not call any of the methods of {@link android.content.ContentResolver} or
1192    {@link android.content.ContentProvider}. Instead, it sends an intent that starts an activity,
1193    which is often part of the provider's own application. The destination activity is in charge of
1194    retrieving and displaying the data in its UI. Depending on the action in the intent, the
1195    destination activity may also prompt the user to make modifications to the provider's data.
1196    An intent may also contain &quot;extras&quot; data that the destination activity displays
1197    in the UI; the user then has the option of changing this data before using it to modify the
1198    data in the provider.
1199</p>
1200<p>
1201
1202</p>
1203<p>
1204    You may want to use intent access to help ensure data integrity. Your provider may depend
1205    on having data inserted, updated, and deleted according to strictly defined business logic. If
1206    this is the case, allowing other applications to directly modify your data may lead to
1207    invalid data. If you want developers to use intent access, be sure to document it thoroughly.
1208    Explain to them why intent access using your own application's UI is better than trying to
1209    modify the data with their code.
1210</p>
1211<p>
1212    Handling an incoming intent that wishes to modify your provider's data is no different from
1213    handling other intents. You can learn more about using intents by reading the topic
1214    <a href="{@docRoot}guide/components/intents-filters.html">Intents and Intent Filters</a>.
1215</p>
1216