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