content-providers.jd revision f013e1afd1e68af5e3b868c26a653bbfb39538f8
1page.title=Content Providers
2@jd:body
3
4<div id="qv-wrapper">
5<div id="qv">
6<h2>Key classes</h2>
7<ol>
8<li>{@link android.content.ContentProvider}</li>
9<li>{@link android.content.ContentResolver}</li>
10<li>{@link android.database.Cursor}</li>
11</ol>
12
13<h2>In this document</h2>
14<ol>
15<li><a href="#basics">Content provider basics</a></li>
16<li><a href="#querying">Querying a content provider</a></li>
17<li><a href="#modifying">Modifying data in a provider</a></li>
18<li><a href="#creating">Creating a content provider</a></li>
19<li><a href="#urisum">Content URI summary</a></li>
20</ol>
21</div>
22</div>
23
24<p>
25Content providers store and retrieve data and make it accessible to all 
26applications.  They're the only way to share data across applications; there's 
27no common storage area that all Android packages can access.
28</p>   
29
30<p>
31Android ships with a number of content providers for common data types 
32(audio, video, images, personal contact information, and so on).  You can 
33see some of them listed in the {@link android.provider android.provider} 
34package.  You can query these providers for the data they contain (although,
35for some, you must acquire the proper permission to read the data).
36</p>   
37
38<p>
39If you want to make your own data public, you have two options:  You can 
40create your own content provider (a {@link android.content.ContentProvider} 
41subclass) or you can add the data to an existing provider &mdash; if there's 
42one that controls the same type of data and you have permission to write to it. 
43</p>   
44
45<p>
46This document is an introduction to using content providers.  After a 
47brief discussion of the fundamentals, it explores how to query a content 
48provider, how to modify data controlled by a provider, and how to create
49a content provider of your own.
50</p>   
51
52
53<h2><a name="basics"></a>Content Provider Basics</h2>
54
55<p>
56How a content provider actually stores its data under the covers is 
57up to its designer.  But all content providers implement a common interface 
58for querying the provider and returning results &mdash; as well as for 
59adding, altering, and deleting data.
60</p>   
61
62<p>
63It's an interface that clients use indirectly, most generally through 
64{@link android.content.ContentResolver} objects.  You get a ContentResolver 
65by calling <code>{@link android.content.Context#getContentResolver 
66getContentResolver()}</code> from within the implementation of an Activity 
67or other application component:
68</p>   
69
70<pre>ContentResolver cr = getContentResolver();</pre>
71
72<p>
73You can then use the ContentResolver's methods to interact with whatever 
74content providers you're interested in.
75</p>   
76
77<p>
78When a query is initiated, the Android system identifies the content provider 
79that's the target of the query and makes sure that it is up and running.  
80The system instantiates all ContentProvider objects; you never need to do it 
81on your own.  In fact, you never deal directly with ContentProvider objects 
82at all.  Typically, there's just a single instance of each type of 
83ContentProvider.  But it can communicate with multiple ContentResolver objects 
84in different applications and processes.  The interaction between processes is 
85handled by the ContentResolver and ContentProvider classes.
86</p>   
87
88
89<h3>The data model</h3>
90
91<p>
92Content providers expose their data as a simple table on a database model, 
93where each row is a record and each column is data of a particular type 
94and meaning.  For example, information about people and their phone numbers 
95might be exposed as follows: 
96</p>   
97
98<table>
99   <tr>
100      <th scope="col">_ID</th>
101      <th scope="col">NUMBER</th>
102      <th scope="col">NUMBER_KEY</th>
103      <th scope="col">LABEL</th>
104      <th scope="col">NAME</th>
105      <th scope="col">TYPE</th>
106   </tr>
107   <tr>
108      <td>13</td>
109      <td>(425) 555 6677</td>
110      <td>425 555 6677</td>
111      <td>Kirkland office</td>
112      <td>Bully Pulpit</td>
113      <td>{@code TYPE_WORK}</td>
114   </tr>
115   <tr>
116      <td>44</td>
117      <td>(212) 555-1234</td>
118      <td>212 555 1234</td>
119      <td>NY apartment</td>
120      <td>Alan Vain</td>
121      <td>{@code TYPE_HOME}</td>
122   </tr>
123   <tr>
124      <td>45</td>
125      <td>(212) 555-6657</td>
126      <td>212 555 6657</td>
127      <td>Downtown office</td>
128      <td>Alan Vain</td>
129      <td>{@code TYPE_MOBILE}</td>
130   </tr>
131   <tr>
132      <td>53</td>
133      <td>201.555.4433</td>
134      <td>201 555 4433</td>
135      <td>Love Nest</td>
136      <td>Rex Cars</td>
137      <td>{@code TYPE_HOME}</td>
138   </tr>
139</table>
140
141<p>
142Every record includes a numeric {@code _ID} field that uniquely identifies 
143the record within the table.  IDs can be used to match records in related 
144tables &mdash; for example, to find a person's phone number in one table 
145and pictures of that person in another.
146</p>   
147
148<p>
149A query returns a {@link android.database.Cursor} object that can move from 
150record to record and column to column to read the contents of each field.  
151It has specialized methods for reading each type of data.  So, to read a field, 
152you must know what type of data the field contains.  (There's more on query 
153results and Cursor objects later.)
154</p>   
155
156
157<h3><a name="uri"></a>URIs</h3>
158
159<p>
160Each content provider exposes a public URI (wrapped as a {@link android.net.Uri} 
161object) that uniquely identifies its data set.  A content provider that controls 
162multiple data sets (multiple tables) exposes a separate URI for each one.  All 
163URIs for providers begin with the string "{@code content://}".  The {@code content:} 
164scheme identifies the data as being controlled by a content provider.
165</p>   
166
167<p>
168If you're defining a content provider, it's a good idea to also define a 
169constant for its URI, to simplify client code and make future updates cleaner.  
170Android defines {@code CONTENT_URI} constants for all the providers that come 
171with the platform.  For example, the URI for the table that matches 
172phone numbers to people and the URI for the table that holds pictures of 
173people (both controlled by the Contacts content provider) are:
174</p>   
175
176<p>
177<p style="margin-left: 2em">{@code android.provider.Contacts.Phones.CONTENT_URI}
178<br/>{@code android.provider.Contacts.Photos.CONTENT_URI}
179</p>   
180
181<p>
182Similarly, the URIs for the table of recent phone calls and the table 
183of calendar entries are:
184</p>   
185
186<p>
187<p style="margin-left: 2em">{@code android.provider.CallLog.Calls.CONTENT_URI}
188<br/>{@code android.provider.Calendar.CONTENT_URI}
189</p>   
190
191<p>
192The URI constant is used in all interactions with the content provider. 
193Every {@link android.content.ContentResolver} method takes the URI 
194as its first argument.  It's what identifies which provider the ContentResolver 
195should talk to and which table of the provider is being targeted.
196</p>   
197
198
199<h2><a name="querying"></a>Querying a Content Provider</h2>
200
201<p>
202You need three pieces of information to query a content provider:
203</p>   
204
205<ul>
206<li>The URI that identifies the provider</li>
207<li>The names of the data fields you want to receive</li>
208<li>The data types for those fields</li>
209</ul>
210
211<p>
212If you're querying a particular record, you also need the ID for that record.
213</p>   
214
215
216<h3>Making the query</h3>
217
218<p>
219To query a content provider, you can use either the 
220<code>{@link android.content.ContentResolver#query ContentResolver.query()}</code> 
221method or the <code>{@link  android.app.Activity#managedQuery 
222Activity.managedQuery()}</code> method. 
223Both methods take the same set of arguments, and both return a 
224Cursor object.  However, {@code managedQuery()} 
225causes the activity to manage the life cycle of the Cursor.  A managed Cursor 
226handles all of the niceties, such as unloading itself when the activity pauses, 
227and requerying itself when the activity restarts.  You can ask an Activity to 
228begin managing an unmanaged Cursor object for you by calling 
229<code>{@link android.app.Activity#startManagingCursor 
230Activity.startManagingCursor()}</code>. 
231</p>   
232
233<p>
234The first argument to either <code>{@link android.content.ContentResolver#query query()}</code> 
235or <code>{@link android.app.Activity#managedQuery managedQuery()}</code> is the provider URI 
236&mdash; the {@code CONTENT_URI} constant that identifies a particular 
237ContentProvider and data set (see <a href="#uri">URIs</a> earlier).
238</p>   
239
240<p>
241To restrict a query to just one record, you can append the {@code _ID} value for 
242that record to the URI &mdash; that is, place a string matching the ID as the 
243last segment of the path part of the URI.  For example, if the ID is 23, 
244the URI would be:
245</p>   
246
247<p style="margin-left: 2em">{@code content://. . . ./23}</p>   
248
249<p>
250There are some helper methods, particularly 
251<code>{@link android.content.ContentUris#withAppendedId 
252ContentUris.withAppendedId()}</code> and <code>{@link 
253android.net.Uri#withAppendedPath Uri.withAppendedPath()}</code>, 
254that make it easy to append an ID to a URI.  Both are static methods that return 
255a Uri object with the ID added.  So, for example, if you were looking for record 
25623 in the database of people contacts, you might construct a query as follows:
257</p>   
258
259<pre>
260import android.provider.Contacts.People;
261import android.content.ContentUris;
262import android.net.Uri;
263import android.database.Cursor;
264
265// Use the ContentUris method to produce the base URI for the contact with _ID == 23.
266Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, 23);
267
268// Alternatively, use the Uri method to produce the base URI.
269// It takes a string rather than an integer.
270Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI, "23");
271
272// Then query for this specific record:
273Cursor cur = managedQuery(myPerson, null, null, null, null);
274</pre>
275
276<p>
277The other arguments to the <code>{@link android.content.ContentResolver#query query()}</code> 
278and <code>{@link android.app.Activity#managedQuery managedQuery()}</code> methods delimit 
279the query in more detail.  They are:
280</p>   
281
282<ul>
283<li>The names of the data columns that should be returned.  A {@code null} 
284value returns all columns.  Otherwise, only columns that are listed by name
285are returned.  All the content providers that come with the platform define 
286constants for their columns.  For example, the 
287{@link android.provider.Contacts.Phones android.provider.Contacts.Phones} class 
288defines constants for the names of the columns in the phone table illustrated 
289earlier &mdash {@code _ID}, {@code NUMBER}, {@code NUMBER_KEY}, {@code NAME},
290and so on.</li>
291
292<li><p>A filter detailing which rows to return, formatted as an SQL {@code WHERE} 
293clause (excluding the {@code WHERE} itself).  A {@code null} value returns 
294all rows (unless the URI limits the query to a single record).</p></li>
295
296<li><p>Selection arguments.</p></li>
297
298<li><p>A sorting order for the rows that are returned, formatted as an SQL 
299{@code ORDER BY} clause (excluding the {@code ORDER BY} itself).  A {@code null} 
300value returns the records in the default order for the table, which may be
301unordered.</p></li>  
302</ul>
303
304<p>
305Let's look at an example query to retrieve a list of contact names and their 
306primary phone numbers:
307</p>
308
309<pre>
310import android.provider.Contacts.People;
311import android.database.Cursor;
312
313// Form an array specifying which columns to return. 
314String[] projection = new String[] {
315                             People._ID,
316                             People._COUNT,
317                             People.NAME,
318                             People.NUMBER
319                          };
320
321// Get the base URI for the People table in the Contacts content provider.
322Uri contacts =  People.CONTENT_URI;
323
324// Make the query. 
325Cursor managedCursor = managedQuery(contacts,
326                         projection, // Which columns to return 
327                         null,       // Which rows to return (all rows)
328                         null,       // Selection arguments (none)
329                         // Put the results in ascending order by name
330                         People.NAME + " ASC");
331</pre>
332
333<p>
334This query retrieves data from the People table of the Contacts content 
335provider.  It gets the name, primary phone number, and unique record ID for
336each contact.  It also reports the number of records that are returned as 
337the {@code _COUNT} field of each record.
338</p>
339
340<p>
341The constants for the names of the columns are defined in various interfaces 
342&mdash; {@code _ID} and {@code _COUNT} in 
343{@link android.provider.BaseColumns BaseColumns}, {@code NAME} in {@link android.provider.Contacts.PeopleColumns PeopleColumns}, and {@code NUMBER} 
344in {@link android.provider.Contacts.PhonesColumns PhoneColumns}.  The 
345{@link android.provider.Contacts.People Contacts.People} class implements 
346each of these interfaces, which is why the code example above could refer 
347to them using just the class name. 
348</p>
349
350
351<h3>What a query returns</h3>
352
353<p>
354A query returns a set of zero or more database records.  The names of the 
355columns, their default order, and their data types are specific to each 
356content provider. 
357But every provider has an {@code _ID} column, which holds a unique numeric 
358ID for each record.  Every provider can also report the number
359of records returned as the {@code _COUNT} column; its value 
360is the same for all rows. 
361</p>
362
363<p> 
364Here is an example result set for the query in the previous section:
365</p>
366
367<table border="1">
368   <tbody>
369      <tr>
370         <th scope="col">_ID</th>
371         <th scope="col">_COUNT</th>
372         <th scope="col">NAME</th>
373         <th scope="col">NUMBER</th>     
374      </tr>
375      <tr>
376         <td>44</td>
377         <td>3</td>
378         <td>Alan Vain</td>
379         <td>212 555 1234</td>   
380      </tr>
381      <tr>
382         <td>13</td>
383         <td>3</td>
384         <td>Bully Pulpit</td>
385         <td>425 555 6677</td>   
386      </tr>
387      <tr>
388         <td>53</td>
389         <td>3</td>
390         <td>Rex Cars</td>
391         <td>201 555 4433</td>
392      </tr>
393   </tbody>
394</table>
395
396<p>
397The retrieved data is exposed by a {@link android.database.Cursor Cursor} 
398object that can be used to iterate backward or forward through the result 
399set.  You can use this object only to read the data.  To add, modify, or 
400delete data, you must use a ContentResolver object.
401</p>
402
403
404<h3>Reading retrieved data</h3>
405
406<p>
407The Cursor object returned by a query provides access to a recordset of
408results.  If you have queried for a specific record by ID, this set will
409contain only one value.  Otherwise, it can contain multiple values.  
410(If there are no matches, it can also be empty.)  You 
411can read data from specific fields in the record, but you must know the 
412data type of the field, because the Cursor object has a separate method
413for reading each type of data &mdash; such as <code>{@link 
414android.database.Cursor#getString getString()}</code>, <code>{@link 
415android.database.Cursor#getInt getInt()}</code>, and <code>{@link 
416android.database.Cursor#getFloat getFloat()}</code>.  
417(However, for most types, if you call the method for reading strings, 
418the Cursor object will give you the String representation of the data.)  
419The Cursor lets you request the column name from the index of the column, 
420or the index number from the column name.
421</p>
422
423<p>
424The following snippet demonstrates reading names and phone numbers from
425the query illustrated earlier:
426</p>
427
428<pre>
429import android.provider.Contacts.People;
430
431private void getColumnData(Cursor cur){ 
432    if (cur.moveToFirst()) {
433
434        String name; 
435        String phoneNumber; 
436        int nameColumn = cur.getColumnIndex(People.NAME); 
437        int phoneColumn = cur.getColumnIndex(People.NUMBER);
438        String imagePath; 
439    
440        do {
441            // Get the field values
442            name = cur.getString(nameColumn);
443            phoneNumber = cur.getString(phoneColumn);
444           
445	    // Do something with the values. 
446            ... 
447
448        } while (cur.moveToNext());
449
450    }
451}
452</pre>
453
454<p>
455If a query can return binary data, such as an image or sound, the data 
456may be directly entered in the table or the table entry for that data may be
457a string specifying a {@code content:} URI that you can use to get the data.  
458In general, smaller amounts of data (say, from 20 to 50K or less) are most often 
459directly entered in the table and can be read by calling 
460<code>{@link android.database.Cursor#getBlob Cursor.getBlob()}</code>.  
461It returns a byte array.
462</p>
463  
464<p>
465If the table entry is a {@code content:} URI, you should never try to open 
466and read the file directly (for one thing, permissions problems can make this 
467fail).  Instead, you should call 
468<code>{@link android.content.ContentResolver#openInputStream 
469ContentResolver.openInputStream()}</code> to get an 
470{@link java.io.InputStream} object that you can use to read the data.  
471</p>
472
473
474<h2><a name="modifying"></a>Modifying Data</h2>
475
476<p>
477Data kept by a content provider can be modified by:
478</p>
479
480<ul>
481<p><li>Adding new records</li>
482<li>Adding new values to existing records</li>
483<li>Batch updating existing records</li>
484<li>Deleting records</li>
485</ul>
486
487<p>
488All data modification is accomplished using {@link android.content.ContentResolver}
489methods.  Some content providers require a more restrictive permission for writing
490data than they do for reading it.  If you don't have permission to write to a 
491content provider, the ContentResolver methods will fail.
492</p>
493
494
495<h3>Adding records</h3>
496
497<p>
498To add a new record to a content provider, first set up a map of key-value pairs 
499in a {@link android.content.ContentValues} object, where each key matches 
500the name of a column in the content provider and the value is the desired 
501value for the new record in that column.  Then call <code>{@link 
502android.content.ContentResolver#insert ContentResolver.insert()}</code> and pass 
503it the URI of the provider and the ContentValues map.  This method returns 
504the full URI of the new record &mdash; that is, the provider's URI with 
505the appended ID for the new record.  You can then use this URI to query and 
506get a Cursor over the new record, and to further modify the record.  
507Here's an example:
508</p>
509
510<pre>
511import android.provider.Contacts.People;
512import android.content.ContentResolver;
513import android.content.ContentValues; 
514
515ContentValues values = new ContentValues();
516
517// Add Abraham Lincoln to contacts and make him a favorite.
518values.put(People.NAME, "Abraham Lincoln");
519// 1 = the new contact is added to favorites
520// 0 = the new contact is not added to favorites
521values.put(People.STARRED, 1);
522
523Uri uri = getContentResolver().insert(People.CONTENT_URI, values);
524</pre>
525
526
527<h3>Adding new values</h3>
528
529<p>
530Once a record exists, you can add new information to it or modify 
531existing information.  For example, the next step in the example above would 
532be to add contact information &mdash; like a phone number or an IM or e-mail 
533address &mdash; to the new entry.  
534</p>
535
536<p>
537The best way to add to a record in the Contacts database is to append 
538the name of the table where the new data goes to the URI for the 
539record, then use the amended URI to add the new data values.  Each
540Contacts table exposes a name for this purpose as a {@code 
541CONTENT_DIRECTORY} constant.  The following code continues the previous 
542example by adding a phone number and e-mail address for the record
543just created:
544</p>
545
546<pre>
547Uri phoneUri = null;
548Uri emailUri = null;
549
550// Add a phone number for Abraham Lincoln.  Begin with the URI for
551// the new record just returned by insert(); it ends with the _ID
552// of the new record, so we don't have to add the ID ourselves.
553// Then append the designation for the phone table to this URI,
554// and use the resulting URI to insert the phone number.
555phoneUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY);
556
557values.clear();
558values.put(People.Phones.TYPE, People.Phones.TYPE_MOBILE);
559values.put(People.Phones.NUMBER, "1233214567");
560getContentResolver().insert(phoneUri, values);
561
562// Now add an email address in the same way.
563emailUri = Uri.withAppendedPath(uri, People.ContactMethods.CONTENT_DIRECTORY);
564
565values.clear();
566// ContactMethods.KIND is used to distinguish different kinds of
567// contact methods, such as email, IM, etc. 
568values.put(People.ContactMethods.KIND, Contacts.KIND_EMAIL);
569values.put(People.ContactMethods.DATA, "test@example.com");
570values.put(People.ContactMethods.TYPE, People.ContactMethods.TYPE_HOME);
571getContentResolver().insert(emailUri, values);   
572</pre>
573
574<p>
575You can place small amounts of binary data into a table by calling 
576the version of <code>{@link android.content.ContentValues#put 
577ContentValues.put()}</code> that takes a byte array.  
578That would work for a small icon-like image or a short audio clip, for example.  
579However, if you have a large amount of binary data to add, such as a photograph
580or a complete song, put a {@code content:} URI for the data in the table and call
581<code>{@link android.content.ContentResolver#openOutputStream 
582ContentResolver.openOutputStream()}</code> 
583with the file's URI.  (That causes the content provider to store the data 
584in a file and record the file path in a hidden field of the record.)
585</p>
586
587<p>
588In this regard, the {@link android.provider.MediaStore} content 
589provider, the main provider that dispenses image, audio, and video 
590data, employs a special convention:  The same URI that is used with 
591{@code query()} or {@code managedQuery()} to get meta-information 
592about the binary data (such as, the caption of a photograph or the
593date it was taken) is used with {@code openInputStream()} 
594to get the data itself.  Similarly, the same URI that is used with
595{@code insert()} to put meta-information into a MediaStore record 
596is used with {@code openOutputStream()} to place the binary data there.
597The following code snippet illustrates this convention:
598</p>
599
600<pre>
601import android.provider.MediaStore.Images.Media;
602import android.content.ContentValues;
603import java.io.OutputStream;
604
605// Save the name and description of an image in a ContentValues map.  
606ContentValues values = new ContentValues(3);
607values.put(Media.DISPLAY_NAME, "road_trip_1");
608values.put(Media.DESCRIPTION, "Day 1, trip to Los Angeles");
609values.put(Media.MIME_TYPE, "image/jpeg");
610
611// Add a new record without the bitmap, but with the values just set.
612// insert() returns the URI of the new record.
613Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
614
615// Now get a handle to the file for that record, and save the data into it.
616// Here, sourceBitmap is a Bitmap object representing the file to save to the database.
617try {
618    OutputStream outStream = getContentResolver().openOutputStream(uri);
619    sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
620    outStream.close();
621} catch (Exception e) {
622    Log.e(TAG, "exception while writing image", e);
623}
624</pre>
625
626
627<h3>Batch updating records</h3>
628
629<p>
630To batch update a group of records (for example, to change "NY" to "New York" 
631in all fields), call the <code>{@link 
632android.content.ContentResolver#update ContentResolver.update()}</code> 
633method with the columns and values to change.
634</p>
635
636
637<h3><a name="deletingrecord"></a>Deleting a record</h3>
638
639<p>
640To delete a single record, call {<code>{@link 
641android.content.ContentResolver#delete ContentResolver.delete()}</code> 
642with the URI of a specific row.
643</p>
644
645<p>
646To delete multiple rows, call <code>{@link 
647android.content.ContentResolver#delete ContentResolver.delete()}</code> 
648with the URI of the type of record to delete (for example, {@code android.provider.Contacts.People.CONTENT_URI}) and an SQL {@code WHERE} 
649clause defining which rows to delete.  (<i><b>Caution</b>: 
650Be sure to include a valid {@code WHERE} clause if you're deleting a general 
651type, or you risk deleting more records than you intended!</i>).
652</p>
653
654
655<h2><a name="creating"></a>Creating a Content Provider</h2>
656
657<p>
658To create a content provider, you must:
659</p>
660
661<ul>
662<li>Set up a system for storing the data.  Most content providers 
663store their data using Android's file storage methods or SQLite databases, 
664but you can store your data any way you want.  Android provides the
665{@link android.database.sqlite.SQLiteOpenHelper SQLiteOpenHelper}
666class to help you create a database and {@link 
667android.database.sqlite.SQLiteDatabase SQLiteDatabase} to manage it.</li>
668
669<li><p>Extend the {@link android.content.ContentProvider} class to provide 
670access to the data.</p></li>
671
672<li><p>Declare the content provider in the manifest file for your 
673application (AndroidManifest.xml).</p></li>
674</ul>
675
676<p>
677The following sections have notes on the last two of these tasks.
678</p>
679
680
681<h3>Extending the ContentProvider class</h3>
682
683<p>
684You define a {@link android.content.ContentProvider} subclass to 
685expose your data to others using the conventions expected by 
686ContentResolver and Cursor objects.  Principally, this means 
687implementing six abstract methods declared in the ContentProvider class:
688</p>
689
690<p style="margin-left: 2em">{@code query()}
691<br/>{@code insert()}
692<br/>{@code update()}
693<br/>{@code delete()}
694<br/>{@code getType()}
695<br/>{@code onCreate()}</p>
696
697<p>
698The {@code query()} method must return a {@link android.database.Cursor} object 
699that can iterate over the requested data.  Cursor itself is an interface, but
700Android provides some ready-made Cursor objects that you can use.  For example,
701{@link android.database.sqlite.SQLiteCursor} can iterate over data stored in
702an SQLite database.  You get the Cursor object by calling any of the {@link 
703android.database.sqlite.SQLiteDatabase SQLiteDatabase} class's {@code query()}
704methods.  There are other Cursor implementations &mdash; such as {@link 
705android.database.MatrixCursor} &mdash; for data not stored in a database.
706</p>
707
708<p>
709Because these ContentProvider methods can be called from 
710various ContentResolver objects in different processes and threads, 
711they must be implemented in a thread-safe manner. 
712</p>
713
714<p>
715As a courtesy, you might also want to call <code>{@link android.content.ContentResolver#notifyChange(android.net.Uri,android.database.ContentObserver)
716ContentResolver.notifyChange()}</code> to notify listeners when there are 
717modifications to the data. 
718</p>
719
720<p>
721Beyond defining the subclass itself, there are other steps you should take
722to simplify the work of clients and make the class more accessible: 
723</p>
724
725<ul>
726<li>Define a {@code public static final} {@link android.net.Uri} 
727named {@code CONTENT_URI}.  This is the string that represents the full 
728{@code content:} URI that your content provider handles.  You must define a 
729unique string for this value.  The best solution is to use the fully-qualified 
730class name of the content provider (made lowercase).  So, for example, the 
731URI for a TransportationProvider class could be defined as follows:
732
733<pre>public static final Uri CONTENT_URI = 
734               Uri.parse("content://com.example.codelab.transporationprovider");</pre>
735
736<p>
737If the provider has subtables, also define {@code CONTENT_URI} constants for
738each of the subtables.  These URIs should all have the same authority (since
739that identifies the content provider), and be distinguished only by their paths. 
740For example:
741</p>
742
743<p style="margin-left: 2em">{@code content://com.example.codelab.transporationprovider/train} 
744<br/>{@code content://com.example.codelab.transporationprovider/air/domestic}
745<br/>{@code content://com.example.codelab.transporationprovider/air/international}</p>
746
747<p>
748For an overview of {@code content:} URIs, see the <a href="#urisum">Content URI 
749Summary</a> at the end of this document.
750</p></li>
751
752<li><p>Define the column names that the content provider will return to clients. 
753If you are using an underlying database, these column names are typically 
754identical to the SQL database column names they represent.  Also define
755{@code public static} String constants that clients can use to specify 
756the columns in queries and other instructions.
757</p>
758
759<p>
760Be sure to include an integer column named "{@code _id}" 
761(with the constant {@code _ID}) for 
762the IDs of the records.  You should have this field whether or not you have 
763another field (such as a URL) that is also unique among all records.  If 
764you're using the SQLite database, the {@code _ID} field should be the 
765following type:
766</p>
767
768<p style="margin-left: 2em">{@code INTEGER PRIMARY KEY AUTOINCREMENT}</p>
769
770<p>
771The {@code AUTOINCREMENT} descriptor is optional.  But without it, SQLite
772increments an ID counter field to the next number above the largest
773existing number in the column.  If you delete the last row, the next row added
774will have the same ID as the deleted row.  {@code AUTOINCREMENT} avoids this 
775by having SQLite increment to the next largest value whether deleted or not.
776</p>
777</li>
778
779<li><p>Carefully document the data type of each column.  Clients need this
780information to read the data.</p></li>
781
782<li><p>If you are handling a new data type, you must define a new MIME type 
783to return in your implementation of <code>{@link 
784android.content.ContentProvider#getType ContentProvider.getType()}</code>.  
785The type depends in part on whether or not the {@code content:} URI submitted 
786to {@code getType()} limits the request to a specific record.  There's one 
787form of the MIME type for a single record and another for multiple records.  
788Use the {@link android.net.Uri Uri} methods to help determine what is being 
789requested.  Here is the general format for each type:</p></li>
790
791<ul>
792<li><p>For a single record:&nbsp;&nbsp;&nbsp; {@code vnd.android.cursor.item/vnd.<em>yourcompanyname.contenttype</em}</p> 
793
794<p>For example, a request for train record 122, like this URI,</p>
795<p style="margin-left: 2em">{@code content://com.example.transportationprovider/trains/122}</p>
796
797<p>might return this MIME type:</p>
798<p style="margin-left: 2em">{@code vnd.android.cursor.item/vnd.example.rail}</p>
799</li>
800
801<li><p>For multiple records:&nbsp;&nbsp;&nbsp; {@code vnd.android.cursor.dir/vnd.<em>yourcompanyname.contenttype</em>}</p>
802
803<p>For example, a request for all train records, like the following URI,</p>
804<p style="margin-left: 2em">{@code content://com.example.transportationprovider/trains}</p>
805
806<p>might return this MIME type:</p>
807<p style="margin-left: 2em">{@code vnd.android.cursor.dir/vnd.example.rail}</p>
808</li>
809</ul>
810
811<li><p>If you are exposing byte data that's too big to put in the table itself
812&mdash; such as a large bitmap file &mdash; the field that exposes the
813data to clients should actually contain a {@code content:} URI string.
814This is the field that gives clients access to the data file.  The record 
815should also have another field, named "{@code _data}" that lists the exact file 
816path on the device for that file.  This field is not intended to be read by 
817the client, but by the ContentResolver.  The client will call <code>{@link 
818android.content.ContentResolver#openInputStream ContentResolver.openInputStream()}</code> 
819on the user-facing field holding the URI for the item.  The ContentResolver 
820will request the "{@code _data}" field for that record, and because
821it has higher permissions than a client, it should be able to access
822that file directly and return a read wrapper for the file to the client.</p></li>
823
824</ul>
825
826<p>
827For an example of a private content provider implementation, see the 
828NodePadProvider class in the Notepad sample application that ships with the SDK.
829</p>
830
831
832<h3>Declaring the content provider</h3>
833
834<p>
835To let the Android system know about the content provider you've developed, 
836declare it with a {@code &lt;provider&gt;} element in the application's 
837AndroidManifest.xml file.  Content providers that are not declared in the
838manifest are not visible to the Android system
839</p>
840
841<p>
842The {@code name} attribute is the fully qualified name of the ContentProvider
843subclass.  The {@code authorities} attribute is the authority part of the 
844{@code content:} URI that identifies the provider.
845For example if the ContentProvider subclass is AutoInfoProvider, the 
846{@code &lt;provider&gt;} element might look like this:
847</p>
848
849<pre>
850&lt;provider name="com.example.autos.AutoInfoProvider"
851          authorities="com.example.autos.autoinfoprovider" 
852          . . . /&gt
853&lt;/provider&gt;
854</pre>
855
856<p>
857Note that the {@code authorities} attribute omits the path part of a 
858{@code content:} URI.  For example, if AutoInfoProvider controlled subtables
859for different types of autos or different manufacturers,
860</p>
861
862<p style="margin-left: 2em">{@code content://com.example.autos.autoinfoprovider/honda}
863<br/>{@code content://com.example.autos.autoinfoprovider/gm/compact}
864<br/>{@code content://com.example.autos.autoinfoprovider/gm/suv}</p>
865
866<p>
867those paths would not be declared in the manifest.  The authority is what 
868identifies the provider, not the path; your provider can interpret the path 
869part of the URI in any way you choose.
870</p>
871
872<p>
873Other {@code &lt;provider&gt;} attributes can set permissions to read and 
874write data, provide for an icon and text that can be displayed to users, 
875enable and disable the provider, and so on.  Set the {@code multiprocess} 
876attribute to "{@code true}" if data does not need to be synchronized between 
877multiple running versions of the content provider.  This permits an instance 
878of the provider to be created in each client process, eliminating the need 
879to perform IPC. 
880</p>
881
882
883<h2><a name="urisum"></a>Content URI Summary</h2>
884
885<p>
886Here is a recap of the important parts of a content URI:
887</p>
888
889<p>
890<img src="{@docRoot}images/content_uri.png" alt="Elements of a content URI" 
891height="80" width="528">
892</p>
893
894<ol type="A">
895<li>Standard prefix indicating that the data is controlled by a
896content provider. It's never modified.</li>
897
898<li><p>The authority part of the URI; it identifies the content provider. 
899For third-party applications, this should be a fully-qualified class name 
900(reduced to lowercase) to ensure uniqueness.  The authority is declared in 
901the {@code &lt;provider&gt;} element's {@code authorities} attribute:</p>
902
903<pre>&lt;provider name=".TransportationProvider"
904          authorities="com.example.transportationprovider"
905          . . .  &gt;</pre></li>
906
907<li><p>The path that the content provider uses to determine what kind of data is
908being requested.  This can be zero or more segments long.  If the content provider
909exposes only one type of data (only trains, for example), it can be absent.
910If the provider exposes several types, including subtypes, it can be several 
911segments long &mdash; for example, "{@code land/bus}", "{@code land/train}", 
912"{@code sea/ship}", and "{@code sea/submarine}" to give four possibilities.</p></li>
913
914<li><p>The ID of the specific record being requested, if any.  This is the 
915{@code _ID} value of the requested record.  If the request is not limited to
916a single record, this segment and the trailing slash are omitted:</p>
917
918<p style="margin-left: 2em">{@code content://com.example.transportationprovider/trains}</p>
919</li>
920</ol>
921
922
923