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 
      7 <h2>In this document</h2>
      8 <ol>
      9 <li><a href="#basics">Content provider basics</a></li>
     10 <li><a href="#querying">Querying a content provider</a></li>
     11 <li><a href="#modifying">Modifying data in a provider</a></li>
     12 <li><a href="#creating">Creating a content provider</a></li>
     13 <li><a href="#urisum">Content URI summary</a></li>
     14 </ol>
     15 
     16 <h2>Key classes</h2>
     17 <ol>
     18 <li>{@link android.content.ContentProvider}</li>
     19 <li>{@link android.content.ContentResolver}</li>
     20 <li>{@link android.database.Cursor}</li>
     21 </ol>
     22 
     23 <h2>See also</h2>
     24 <ol>
     25   <li><a href="{@docRoot}guide/topics/providers/calendar-provider.html">Calendar Provider</a></li>
     26 </ol>
     27 </div>
     28 </div>
     29 
     30 <p>
     31 Content providers store and retrieve data and make it accessible to all 
     32 applications.  They're the only way to share data across applications; there's 
     33 no common storage area that all Android packages can access.
     34 </p>   
     35 
     36 <p>
     37 Android ships with a number of content providers for common data types 
     38 (audio, video, images, personal contact information, and so on).  You can 
     39 see some of them listed in the {@link android.provider android.provider} 
     40 package.  You can query these providers for the data they contain (although,
     41 for some, you must acquire the proper permission to read the data).
     42 </p>   
     43 
     44 <p class="note"><strong>Note:</strong> Android 4.0 introduces the Calendar
     45 Provider. For more information, see <a
     46 href="{@docRoot}guide/topics/providers/calendar-provider.html">Calendar
     47 Provider</a>.</p>
     48 <p>
     49 If you want to make your own data public, you have two options:  You can 
     50 create your own content provider (a {@link android.content.ContentProvider} 
     51 subclass) or you can add the data to an existing provider &mdash; if there's 
     52 one that controls the same type of data and you have permission to write to it. 
     53 </p>   
     54 
     55 <p>
     56 This document is an introduction to using content providers.  After a 
     57 brief discussion of the fundamentals, it explores how to query a content 
     58 provider, how to modify data controlled by a provider, and how to create
     59 a content provider of your own.
     60 </p>   
     61 
     62 
     63 <h2><a name="basics"></a>Content Provider Basics</h2>
     64 
     65 <p>
     66 How a content provider actually stores its data under the covers is 
     67 up to its designer.  But all content providers implement a common interface 
     68 for querying the provider and returning results &mdash; as well as for 
     69 adding, altering, and deleting data.
     70 </p>   
     71 
     72 <p>
     73 It's an interface that clients use indirectly, most generally through 
     74 {@link android.content.ContentResolver} objects.  You get a ContentResolver 
     75 by calling <code>{@link android.content.Context#getContentResolver 
     76 getContentResolver()}</code> from within the implementation of an Activity 
     77 or other application component:
     78 </p>   
     79 
     80 <pre>ContentResolver cr = getContentResolver();</pre>
     81 
     82 <p>
     83 You can then use the ContentResolver's methods to interact with whatever 
     84 content providers you're interested in.
     85 </p>   
     86 
     87 <p>
     88 When a query is initiated, the Android system identifies the content provider 
     89 that's the target of the query and makes sure that it is up and running.  
     90 The system instantiates all ContentProvider objects; you never need to do it 
     91 on your own.  In fact, you never deal directly with ContentProvider objects 
     92 at all.  Typically, there's just a single instance of each type of 
     93 ContentProvider.  But it can communicate with multiple ContentResolver objects 
     94 in different applications and processes.  The interaction between processes is 
     95 handled by the ContentResolver and ContentProvider classes.
     96 </p>   
     97 
     98 
     99 <h3>The data model</h3>
    100 
    101 <p>
    102 Content providers expose their data as a simple table on a database model, 
    103 where each row is a record and each column is data of a particular type 
    104 and meaning.  For example, information about people and their phone numbers 
    105 might be exposed as follows: 
    106 </p>   
    107 
    108 <table>
    109    <tr>
    110       <th scope="col">_ID</th>
    111       <th scope="col">NUMBER</th>
    112       <th scope="col">NUMBER_KEY</th>
    113       <th scope="col">LABEL</th>
    114       <th scope="col">NAME</th>
    115       <th scope="col">TYPE</th>
    116    </tr>
    117    <tr>
    118       <td>13</td>
    119       <td>(425) 555 6677</td>
    120       <td>425 555 6677</td>
    121       <td>Kirkland office</td>
    122       <td>Bully Pulpit</td>
    123       <td>{@code TYPE_WORK}</td>
    124    </tr>
    125    <tr>
    126       <td>44</td>
    127       <td>(212) 555-1234</td>
    128       <td>212 555 1234</td>
    129       <td>NY apartment</td>
    130       <td>Alan Vain</td>
    131       <td>{@code TYPE_HOME}</td>
    132    </tr>
    133    <tr>
    134       <td>45</td>
    135       <td>(212) 555-6657</td>
    136       <td>212 555 6657</td>
    137       <td>Downtown office</td>
    138       <td>Alan Vain</td>
    139       <td>{@code TYPE_MOBILE}</td>
    140    </tr>
    141    <tr>
    142       <td>53</td>
    143       <td>201.555.4433</td>
    144       <td>201 555 4433</td>
    145       <td>Love Nest</td>
    146       <td>Rex Cars</td>
    147       <td>{@code TYPE_HOME}</td>
    148    </tr>
    149 </table>
    150 
    151 <p>
    152 Every record includes a numeric {@code _ID} field that uniquely identifies 
    153 the record within the table.  IDs can be used to match records in related 
    154 tables &mdash; for example, to find a person's phone number in one table 
    155 and pictures of that person in another.
    156 </p>   
    157 
    158 <p>
    159 A query returns a {@link android.database.Cursor} object that can move from 
    160 record to record and column to column to read the contents of each field.  
    161 It has specialized methods for reading each type of data.  So, to read a field, 
    162 you must know what type of data the field contains.  (There's more on query 
    163 results and Cursor objects later.)
    164 </p>   
    165 
    166 
    167 <h3><a name="uri"></a>URIs</h3>
    168 
    169 <p>
    170 Each content provider exposes a public URI (wrapped as a {@link android.net.Uri} 
    171 object) that uniquely identifies its data set.  A content provider that controls 
    172 multiple data sets (multiple tables) exposes a separate URI for each one.  All 
    173 URIs for providers begin with the string "{@code content://}".  The {@code content:} 
    174 scheme identifies the data as being controlled by a content provider.
    175 </p>   
    176 
    177 <p>
    178 If you're defining a content provider, it's a good idea to also define a 
    179 constant for its URI, to simplify client code and make future updates cleaner.  
    180 Android defines {@code CONTENT_URI} constants for all the providers that come 
    181 with the platform.  For example, the URI for the table that matches 
    182 phone numbers to people and the URI for the table that holds pictures of 
    183 people (both controlled by the Contacts content provider) are:
    184 </p>   
    185 
    186 <p>
    187 <p style="margin-left: 2em">{@code android.provider.Contacts.Phones.CONTENT_URI}
    188 <br/>{@code android.provider.Contacts.Photos.CONTENT_URI}
    189 </p>
    190 
    191 <p>
    192 The URI constant is used in all interactions with the content provider. 
    193 Every {@link android.content.ContentResolver} method takes the URI 
    194 as its first argument.  It's what identifies which provider the ContentResolver 
    195 should 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>
    202 You 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>
    212 If 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>
    219 To query a content provider, you can use either the 
    220 <code>{@link android.content.ContentResolver#query ContentResolver.query()}</code> 
    221 method or the <code>{@link  android.app.Activity#managedQuery 
    222 Activity.managedQuery()}</code> method. 
    223 Both methods take the same set of arguments, and both return a 
    224 Cursor object.  However, {@code managedQuery()} 
    225 causes the activity to manage the life cycle of the Cursor.  A managed Cursor 
    226 handles all of the niceties, such as unloading itself when the activity pauses, 
    227 and requerying itself when the activity restarts.  You can ask an Activity to 
    228 begin managing an unmanaged Cursor object for you by calling 
    229 <code>{@link android.app.Activity#startManagingCursor 
    230 Activity.startManagingCursor()}</code>. 
    231 </p>   
    232 
    233 <p>
    234 The first argument to either <code>{@link android.content.ContentResolver#query query()}</code> 
    235 or <code>{@link android.app.Activity#managedQuery managedQuery()}</code> is the provider URI 
    236 &mdash; the {@code CONTENT_URI} constant that identifies a particular 
    237 ContentProvider and data set (see <a href="#uri">URIs</a> earlier).
    238 </p>   
    239 
    240 <p>
    241 To restrict a query to just one record, you can append the {@code _ID} value for 
    242 that record to the URI &mdash; that is, place a string matching the ID as the 
    243 last segment of the path part of the URI.  For example, if the ID is 23, 
    244 the URI would be:
    245 </p>   
    246 
    247 <p style="margin-left: 2em">{@code content://. . . ./23}</p>   
    248 
    249 <p>
    250 There are some helper methods, particularly 
    251 <code>{@link android.content.ContentUris#withAppendedId 
    252 ContentUris.withAppendedId()}</code> and <code>{@link 
    253 android.net.Uri#withAppendedPath Uri.withAppendedPath()}</code>, 
    254 that make it easy to append an ID to a URI.  Both are static methods that return 
    255 a Uri object with the ID added.  So, for example, if you were looking for record 
    256 23 in the database of people contacts, you might construct a query as follows:
    257 </p>   
    258 
    259 <pre>
    260 import android.provider.Contacts.People;
    261 import android.content.ContentUris;
    262 import android.net.Uri;
    263 import android.database.Cursor;
    264 
    265 // Use the ContentUris method to produce the base URI for the contact with _ID == 23.
    266 Uri 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.
    270 Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI, "23");
    271 
    272 // Then query for this specific record:
    273 Cursor cur = managedQuery(myPerson, null, null, null, null);
    274 </pre>
    275 
    276 <p>
    277 The other arguments to the <code>{@link android.content.ContentResolver#query query()}</code> 
    278 and <code>{@link android.app.Activity#managedQuery managedQuery()}</code> methods delimit 
    279 the 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} 
    284 value returns all columns.  Otherwise, only columns that are listed by name
    285 are returned.  All the content providers that come with the platform define 
    286 constants for their columns.  For example, the 
    287 {@link android.provider.Contacts.Phones android.provider.Contacts.Phones} class 
    288 defines constants for the names of the columns in the phone table illustrated 
    289 earlier &mdash; {@code _ID}, {@code NUMBER}, {@code NUMBER_KEY}, {@code NAME},
    290 and so on.</li>
    291 
    292 <li><p>A filter detailing which rows to return, formatted as an SQL {@code WHERE} 
    293 clause (excluding the {@code WHERE} itself).  A {@code null} value returns 
    294 all 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} 
    300 value returns the records in the default order for the table, which may be
    301 unordered.</p></li>  
    302 </ul>
    303 
    304 <p>
    305 Let's look at an example query to retrieve a list of contact names and their 
    306 primary phone numbers:
    307 </p>
    308 
    309 <pre>
    310 import android.provider.Contacts.People;
    311 import android.database.Cursor;
    312 
    313 // Form an array specifying which columns to return. 
    314 String[] 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.
    322 Uri contacts =  People.CONTENT_URI;
    323 
    324 // Make the query. 
    325 Cursor 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>
    334 This query retrieves data from the People table of the Contacts content 
    335 provider.  It gets the name, primary phone number, and unique record ID for
    336 each contact.  It also reports the number of records that are returned as 
    337 the {@code _COUNT} field of each record.
    338 </p>
    339 
    340 <p>
    341 The 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} 
    344 in {@link android.provider.Contacts.PhonesColumns PhoneColumns}.  The 
    345 {@link android.provider.Contacts.People Contacts.People} class implements 
    346 each of these interfaces, which is why the code example above could refer 
    347 to them using just the class name. 
    348 </p>
    349 
    350 
    351 <h3>What a query returns</h3>
    352 
    353 <p>
    354 A query returns a set of zero or more database records.  The names of the 
    355 columns, their default order, and their data types are specific to each 
    356 content provider. 
    357 But every provider has an {@code _ID} column, which holds a unique numeric 
    358 ID for each record.  Every provider can also report the number
    359 of records returned as the {@code _COUNT} column; its value 
    360 is the same for all rows. 
    361 </p>
    362 
    363 <p> 
    364 Here 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>
    397 The retrieved data is exposed by a {@link android.database.Cursor Cursor} 
    398 object that can be used to iterate backward or forward through the result 
    399 set.  You can use this object only to read the data.  To add, modify, or 
    400 delete data, you must use a ContentResolver object.
    401 </p>
    402 
    403 
    404 <h3>Reading retrieved data</h3>
    405 
    406 <p>
    407 The Cursor object returned by a query provides access to a recordset of
    408 results.  If you have queried for a specific record by ID, this set will
    409 contain only one value.  Otherwise, it can contain multiple values.  
    410 (If there are no matches, it can also be empty.)  You 
    411 can read data from specific fields in the record, but you must know the 
    412 data type of the field, because the Cursor object has a separate method
    413 for reading each type of data &mdash; such as <code>{@link 
    414 android.database.Cursor#getString getString()}</code>, <code>{@link 
    415 android.database.Cursor#getInt getInt()}</code>, and <code>{@link 
    416 android.database.Cursor#getFloat getFloat()}</code>.  
    417 (However, for most types, if you call the method for reading strings, 
    418 the Cursor object will give you the String representation of the data.)  
    419 The Cursor lets you request the column name from the index of the column, 
    420 or the index number from the column name.
    421 </p>
    422 
    423 <p>
    424 The following snippet demonstrates reading names and phone numbers from
    425 the query illustrated earlier:
    426 </p>
    427 
    428 <pre>
    429 import android.provider.Contacts.People;
    430 
    431 private 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>
    455 If a query can return binary data, such as an image or sound, the data 
    456 may be directly entered in the table or the table entry for that data may be
    457 a string specifying a {@code content:} URI that you can use to get the data.  
    458 In general, smaller amounts of data (say, from 20 to 50K or less) are most often 
    459 directly entered in the table and can be read by calling 
    460 <code>{@link android.database.Cursor#getBlob Cursor.getBlob()}</code>.  
    461 It returns a byte array.
    462 </p>
    463   
    464 <p>
    465 If the table entry is a {@code content:} URI, you should never try to open 
    466 and read the file directly (for one thing, permissions problems can make this 
    467 fail).  Instead, you should call 
    468 <code>{@link android.content.ContentResolver#openInputStream 
    469 ContentResolver.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>
    477 Data 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>
    488 All data modification is accomplished using {@link android.content.ContentResolver}
    489 methods.  Some content providers require a more restrictive permission for writing
    490 data than they do for reading it.  If you don't have permission to write to a 
    491 content provider, the ContentResolver methods will fail.
    492 </p>
    493 
    494 
    495 <h3>Adding records</h3>
    496 
    497 <p>
    498 To add a new record to a content provider, first set up a map of key-value pairs 
    499 in a {@link android.content.ContentValues} object, where each key matches 
    500 the name of a column in the content provider and the value is the desired 
    501 value for the new record in that column.  Then call <code>{@link 
    502 android.content.ContentResolver#insert ContentResolver.insert()}</code> and pass 
    503 it the URI of the provider and the ContentValues map.  This method returns 
    504 the full URI of the new record &mdash; that is, the provider's URI with 
    505 the appended ID for the new record.  You can then use this URI to query and 
    506 get a Cursor over the new record, and to further modify the record.  
    507 Here's an example:
    508 </p>
    509 
    510 <pre>
    511 import android.provider.Contacts.People;
    512 import android.content.ContentResolver;
    513 import android.content.ContentValues; 
    514 
    515 ContentValues values = new ContentValues();
    516 
    517 // Add Abraham Lincoln to contacts and make him a favorite.
    518 values.put(People.NAME, "Abraham Lincoln");
    519 // 1 = the new contact is added to favorites
    520 // 0 = the new contact is not added to favorites
    521 values.put(People.STARRED, 1);
    522 
    523 Uri uri = getContentResolver().insert(People.CONTENT_URI, values);
    524 </pre>
    525 
    526 
    527 <h3>Adding new values</h3>
    528 
    529 <p>
    530 Once a record exists, you can add new information to it or modify 
    531 existing information.  For example, the next step in the example above would 
    532 be to add contact information &mdash; like a phone number or an IM or e-mail 
    533 address &mdash; to the new entry.  
    534 </p>
    535 
    536 <p>
    537 The best way to add to a record in the Contacts database is to append 
    538 the name of the table where the new data goes to the URI for the 
    539 record, then use the amended URI to add the new data values.  Each
    540 Contacts table exposes a name for this purpose as a {@code 
    541 CONTENT_DIRECTORY} constant.  The following code continues the previous 
    542 example by adding a phone number and e-mail address for the record
    543 just created:
    544 </p>
    545 
    546 <pre>
    547 Uri phoneUri = null;
    548 Uri 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.
    555 phoneUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY);
    556 
    557 values.clear();
    558 values.put(People.Phones.TYPE, People.Phones.TYPE_MOBILE);
    559 values.put(People.Phones.NUMBER, "1233214567");
    560 getContentResolver().insert(phoneUri, values);
    561 
    562 // Now add an email address in the same way.
    563 emailUri = Uri.withAppendedPath(uri, People.ContactMethods.CONTENT_DIRECTORY);
    564 
    565 values.clear();
    566 // ContactMethods.KIND is used to distinguish different kinds of
    567 // contact methods, such as email, IM, etc. 
    568 values.put(People.ContactMethods.KIND, Contacts.KIND_EMAIL);
    569 values.put(People.ContactMethods.DATA, "test (a] example.com");
    570 values.put(People.ContactMethods.TYPE, People.ContactMethods.TYPE_HOME);
    571 getContentResolver().insert(emailUri, values);   
    572 </pre>
    573 
    574 <p>
    575 You can place small amounts of binary data into a table by calling 
    576 the version of <code>{@link android.content.ContentValues#put 
    577 ContentValues.put()}</code> that takes a byte array.  
    578 That would work for a small icon-like image or a short audio clip, for example.  
    579 However, if you have a large amount of binary data to add, such as a photograph
    580 or a complete song, put a {@code content:} URI for the data in the table and call
    581 <code>{@link android.content.ContentResolver#openOutputStream 
    582 ContentResolver.openOutputStream()}</code> 
    583 with the file's URI.  (That causes the content provider to store the data 
    584 in a file and record the file path in a hidden field of the record.)
    585 </p>
    586 
    587 <p>
    588 In this regard, the {@link android.provider.MediaStore} content 
    589 provider, the main provider that dispenses image, audio, and video 
    590 data, employs a special convention:  The same URI that is used with 
    591 {@code query()} or {@code managedQuery()} to get meta-information 
    592 about the binary data (such as, the caption of a photograph or the
    593 date it was taken) is used with {@code openInputStream()} 
    594 to get the data itself.  Similarly, the same URI that is used with
    595 {@code insert()} to put meta-information into a MediaStore record 
    596 is used with {@code openOutputStream()} to place the binary data there.
    597 The following code snippet illustrates this convention:
    598 </p>
    599 
    600 <pre>
    601 import android.provider.MediaStore.Images.Media;
    602 import android.content.ContentValues;
    603 import java.io.OutputStream;
    604 
    605 // Save the name and description of an image in a ContentValues map.  
    606 ContentValues values = new ContentValues(3);
    607 values.put(Media.DISPLAY_NAME, "road_trip_1");
    608 values.put(Media.DESCRIPTION, "Day 1, trip to Los Angeles");
    609 values.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.
    613 Uri 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.
    617 try {
    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>
    630 To batch update a group of records (for example, to change "NY" to "New York" 
    631 in all fields), call the <code>{@link 
    632 android.content.ContentResolver#update ContentResolver.update()}</code> 
    633 method with the columns and values to change.
    634 </p>
    635 
    636 
    637 <h3><a name="deletingrecord"></a>Deleting a record</h3>
    638 
    639 <p>
    640 To delete a single record, call {<code>{@link 
    641 android.content.ContentResolver#delete ContentResolver.delete()}</code> 
    642 with the URI of a specific row.
    643 </p>
    644 
    645 <p>
    646 To delete multiple rows, call <code>{@link 
    647 android.content.ContentResolver#delete ContentResolver.delete()}</code> 
    648 with the URI of the type of record to delete (for example, {@code android.provider.Contacts.People.CONTENT_URI}) and an SQL {@code WHERE} 
    649 clause defining which rows to delete.  (<i><b>Caution</b>: 
    650 Be sure to include a valid {@code WHERE} clause if you're deleting a general 
    651 type, 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>
    658 To create a content provider, you must:
    659 </p>
    660 
    661 <ul>
    662 <li>Set up a system for storing the data.  Most content providers 
    663 store their data using Android's file storage methods or SQLite databases, 
    664 but you can store your data any way you want.  Android provides the
    665 {@link android.database.sqlite.SQLiteOpenHelper SQLiteOpenHelper}
    666 class to help you create a database and {@link 
    667 android.database.sqlite.SQLiteDatabase SQLiteDatabase} to manage it.</li>
    668 
    669 <li><p>Extend the {@link android.content.ContentProvider} class to provide 
    670 access to the data.</p></li>
    671 
    672 <li><p>Declare the content provider in the manifest file for your 
    673 application (AndroidManifest.xml).</p></li>
    674 </ul>
    675 
    676 <p>
    677 The 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>
    684 You define a {@link android.content.ContentProvider} subclass to 
    685 expose your data to others using the conventions expected by 
    686 ContentResolver and Cursor objects.  Principally, this means 
    687 implementing 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>
    698 The {@code query()} method must return a {@link android.database.Cursor} object 
    699 that can iterate over the requested data.  Cursor itself is an interface, but
    700 Android provides some ready-made Cursor objects that you can use.  For example,
    701 {@link android.database.sqlite.SQLiteCursor} can iterate over data stored in
    702 an SQLite database.  You get the Cursor object by calling any of the {@link 
    703 android.database.sqlite.SQLiteDatabase SQLiteDatabase} class's {@code query()}
    704 methods.  There are other Cursor implementations &mdash; such as {@link 
    705 android.database.MatrixCursor} &mdash; for data not stored in a database.
    706 </p>
    707 
    708 <p>
    709 Because these ContentProvider methods can be called from 
    710 various ContentResolver objects in different processes and threads, 
    711 they must be implemented in a thread-safe manner. 
    712 </p>
    713 
    714 <p>
    715 As a courtesy, you might also want to call <code>{@link android.content.ContentResolver#notifyChange(android.net.Uri,android.database.ContentObserver)
    716 ContentResolver.notifyChange()}</code> to notify listeners when there are 
    717 modifications to the data. 
    718 </p>
    719 
    720 <p>
    721 Beyond defining the subclass itself, there are other steps you should take
    722 to 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} 
    727 named {@code CONTENT_URI}.  This is the string that represents the full 
    728 {@code content:} URI that your content provider handles.  You must define a 
    729 unique string for this value.  The best solution is to use the fully-qualified 
    730 class name of the content provider (made lowercase).  So, for example, the 
    731 URI 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.transportationprovider");</pre>
    735 
    736 <p>
    737 If the provider has subtables, also define {@code CONTENT_URI} constants for
    738 each of the subtables.  These URIs should all have the same authority (since
    739 that identifies the content provider), and be distinguished only by their paths. 
    740 For example:
    741 </p>
    742 
    743 <p style="margin-left: 2em">{@code content://com.example.codelab.transportationprovider/train} 
    744 <br/>{@code content://com.example.codelab.transportationprovider/air/domestic}
    745 <br/>{@code content://com.example.codelab.transportationprovider/air/international}</p>
    746 
    747 <p>
    748 For an overview of {@code content:} URIs, see the <a href="#urisum">Content URI 
    749 Summary</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. 
    753 If you are using an underlying database, these column names are typically 
    754 identical to the SQL database column names they represent.  Also define
    755 {@code public static} String constants that clients can use to specify 
    756 the columns in queries and other instructions.
    757 </p>
    758 
    759 <p>
    760 Be sure to include an integer column named "{@code _id}" 
    761 (with the constant {@code _ID}) for 
    762 the IDs of the records.  You should have this field whether or not you have 
    763 another field (such as a URL) that is also unique among all records.  If 
    764 you're using the SQLite database, the {@code _ID} field should be the 
    765 following type:
    766 </p>
    767 
    768 <p style="margin-left: 2em">{@code INTEGER PRIMARY KEY AUTOINCREMENT}</p>
    769 
    770 <p>
    771 The {@code AUTOINCREMENT} descriptor is optional.  But without it, SQLite
    772 increments an ID counter field to the next number above the largest
    773 existing number in the column.  If you delete the last row, the next row added
    774 will have the same ID as the deleted row.  {@code AUTOINCREMENT} avoids this 
    775 by 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
    780 information 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 
    783 to return in your implementation of <code>{@link 
    784 android.content.ContentProvider#getType ContentProvider.getType()}</code>.  
    785 The type depends in part on whether or not the {@code content:} URI submitted 
    786 to {@code getType()} limits the request to a specific record.  There's one 
    787 form of the MIME type for a single record and another for multiple records.  
    788 Use the {@link android.net.Uri Uri} methods to help determine what is being 
    789 requested.  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
    813 data to clients should actually contain a {@code content:} URI string.
    814 This is the field that gives clients access to the data file.  The record 
    815 should also have another field, named "{@code _data}" that lists the exact file 
    816 path on the device for that file.  This field is not intended to be read by 
    817 the client, but by the ContentResolver.  The client will call <code>{@link 
    818 android.content.ContentResolver#openInputStream ContentResolver.openInputStream()}</code> 
    819 on the user-facing field holding the URI for the item.  The ContentResolver 
    820 will request the "{@code _data}" field for that record, and because
    821 it has higher permissions than a client, it should be able to access
    822 that file directly and return a read wrapper for the file to the client.</p></li>
    823 
    824 </ul>
    825 
    826 <p>
    827 For an example of a private content provider implementation, see the 
    828 NodePadProvider 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>
    835 To let the Android system know about the content provider you've developed, 
    836 declare it with a {@code &lt;provider&gt;} element in the application's 
    837 AndroidManifest.xml file.  Content providers that are not declared in the
    838 manifest are not visible to the Android system
    839 </p>
    840 
    841 <p>
    842 The {@code name} attribute is the fully qualified name of the ContentProvider
    843 subclass.  The {@code authorities} attribute is the authority part of the 
    844 {@code content:} URI that identifies the provider.
    845 For 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 android:name="com.example.autos.AutoInfoProvider"
    851           android:authorities="com.example.autos.autoinfoprovider" 
    852           . . . /&gt
    853 &lt;/provider&gt;
    854 </pre>
    855 
    856 <p>
    857 Note that the {@code authorities} attribute omits the path part of a 
    858 {@code content:} URI.  For example, if AutoInfoProvider controlled subtables
    859 for 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>
    867 those paths would not be declared in the manifest.  The authority is what 
    868 identifies the provider, not the path; your provider can interpret the path 
    869 part of the URI in any way you choose.
    870 </p>
    871 
    872 <p>
    873 Other {@code &lt;provider&gt;} attributes can set permissions to read and 
    874 write data, provide for an icon and text that can be displayed to users, 
    875 enable and disable the provider, and so on.  Set the {@code multiprocess} 
    876 attribute to "{@code true}" if data does not need to be synchronized between 
    877 multiple running versions of the content provider.  This permits an instance 
    878 of the provider to be created in each client process, eliminating the need 
    879 to perform IPC. 
    880 </p>
    881 
    882 
    883 <h2><a name="urisum"></a>Content URI Summary</h2>
    884 
    885 <p>
    886 Here 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" 
    891 height="80" width="528">
    892 </p>
    893 
    894 <ol type="A">
    895 <li>Standard prefix indicating that the data is controlled by a
    896 content provider. It's never modified.</li>
    897 
    898 <li><p>The authority part of the URI; it identifies the content provider. 
    899 For third-party applications, this should be a fully-qualified class name 
    900 (reduced to lowercase) to ensure uniqueness.  The authority is declared in 
    901 the {@code &lt;provider&gt;} element's {@code authorities} attribute:</p>
    902 
    903 <pre>&lt;provider android:name=".TransportationProvider"
    904           android: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
    908 being requested.  This can be zero or more segments long.  If the content provider
    909 exposes only one type of data (only trains, for example), it can be absent.
    910 If the provider exposes several types, including subtypes, it can be several 
    911 segments 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
    916 a 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