content-provider-basics.jd revision 50e990c64fa23ce94efa76b9e72df7f8ec3cee6a
1page.title=Content Provider Basics 2@jd:body 3<div id="qv-wrapper"> 4<div id="qv"> 5 6 7 <!-- In this document --> 8<h2>In this document</h2> 9<ol> 10 <li> 11 <a href="#Basics">Overview</a> 12 <ol> 13 <li> 14 <a href="#ClientProvider">Accessing a provider</a> 15 </li> 16 <li> 17 <a href="#ContentURIs">Content URIs</a> 18 </li> 19 </ol> 20 </li> 21 <li> 22 <a href="#SimpleQuery">Retrieving Data from the Provider</a> 23 <ol> 24 <li> 25 <a href="#RequestPermissions">Requesting read access permission</a> 26 </li> 27 <li> 28 <a href="#Query">Constructing the query</a> 29 </li> 30 <li> 31 <a href="#DisplayResults">Displaying query results</a> 32 </li> 33 <li> 34 <a href="#GettingResults">Getting data from query results</a> 35 </li> 36 </ol> 37 </li> 38 <li> 39 <a href="#Permissions">Content Provider Permissions</a> 40 </li> 41 <li> 42 <a href="#Modifications">Inserting, Updating, and Deleting Data</a> 43 <ol> 44 <li> 45 <a href="#Inserting">Inserting data</a> 46 </li> 47 <li> 48 <a href="#Updating">Updating data</a> 49 </li> 50 <li> 51 <a href="#Deleting">Deleting data</a> 52 </li> 53 </ol> 54 </li> 55 <li> 56 <a href="#DataTypes">Provider Data Types</a> 57 </li> 58 <li> 59 <a href="#AltForms">Alternative Forms of Provider Access</a> 60 <ol> 61 <li> 62 <a href="#Batch">Batch access</a> 63 </li> 64 <li> 65 <a href="#Intents">Data access via intents</a> 66 </li> 67 </ol> 68 </li> 69 <li> 70 <a href="#ContractClasses">Contract Classes</a> 71 </li> 72 <li> 73 <a href="#MIMETypeReference">MIME Type Reference</a> 74 </li> 75</ol> 76 77 <!-- Key Classes --> 78<h2>Key classes</h2> 79 <ol> 80 <li> 81 {@link android.content.ContentProvider} 82 </li> 83 <li> 84 {@link android.content.ContentResolver} 85 </li> 86 <li> 87 {@link android.database.Cursor} 88 </li> 89 <li> 90 {@link android.net.Uri} 91 </li> 92 </ol> 93 94 <!-- Related Samples --> 95<h2>Related Samples</h2> 96 <ol> 97 <li> 98 <a 99 href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/List2.html"> 100 Cursor (People)</a> 101 </li> 102 <li> 103 <a 104 href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/List7.html"> 105 Cursor (Phones)</a> 106 </li> 107 </ol> 108 109 <!-- See also --> 110<h2>See also</h2> 111 <ol> 112 <li> 113 <a href="{@docRoot}guide/topics/providers/content-provider-creating.html"> 114 Creating a Content Provider</a> 115 </li> 116 <li> 117 <a href="{@docRoot}guide/topics/providers/calendar-provider.html"> 118 Calendar Provider</a> 119 </li> 120 </ol> 121</div> 122</div> 123 124 <!-- Intro paragraphs --> 125<p> 126 A content provider manages access to a central repository of data. A provider 127 is part of an Android application, which often provides its own UI for working with 128 the data. However, content providers are primarily intended to be used by other 129 applications, which access the provider using a provider client object. Together, providers 130 and provider clients offer a consistent, standard interface to data that also handles 131 inter-process communication and secure data access. 132</p> 133<p> 134 This topic describes the basics of the following: 135</p> 136 <ul> 137 <li>How content providers work.</li> 138 <li>The API you use retrieve data from a content provider.</li> 139 <li>The API you use to insert, update, or delete data in a content provider.</li> 140 <li>Other API features that facilitate working with providers.</li> 141 </ul> 142 143 <!-- Basics --> 144<h2 id="Basics">Overview</h2> 145<p> 146 A content provider presents data to external applications as one or more tables that are 147 similar to the tables found in a relational database. A row represents an instance of some type 148 of data the provider collects, and each row in the column represents an individual piece of 149 data collected for an instance. 150</p> 151<p> 152 For example, one of the built-in providers in the Android platform is the user dictionary, which 153 stores the spellings of non-standard words that the user wants to keep. Table 1 illustrates what 154 the data might look like in this provider's table: 155</p> 156<p class="table-caption"> 157 <strong>Table 1:</strong> Sample user dictionary table. 158</p> 159<table id="table1" style="width: 50%;"> 160 <tr> 161 <th style="width:20%" align="center" scope="col">word</th> 162 <th style="width:20%" align="center" scope="col">app id</th> 163 <th style="width:20%" align="center" scope="col">frequency</th> 164 <th style="width:20%" align="center" scope="col">locale</th> 165 <th style="width:20%" align="center" scope="col">_ID</th> 166 </tr> 167 <tr> 168 <td align="center" scope="row">mapreduce</td> 169 <td align="center">user1</td> 170 <td align="center">100</td> 171 <td align="center">en_US</td> 172 <td align="center">1</td> 173 </tr> 174 <tr> 175 <td align="center" scope="row">precompiler</td> 176 <td align="center">user14</td> 177 <td align="center">200</td> 178 <td align="center">fr_FR</td> 179 <td align="center">2</td> 180 </tr> 181 <tr> 182 <td align="center" scope="row">applet</td> 183 <td align="center">user2</td> 184 <td align="center">225</td> 185 <td align="center">fr_CA</td> 186 <td align="center">3</td> 187 </tr> 188 <tr> 189 <td align="center" scope="row">const</td> 190 <td align="center">user1</td> 191 <td align="center">255</td> 192 <td align="center">pt_BR</td> 193 <td align="center">4</td> 194 </tr> 195 <tr> 196 <td align="center" scope="row">int</td> 197 <td align="center">user5</td> 198 <td align="center">100</td> 199 <td align="center">en_UK</td> 200 <td align="center">5</td> 201 </tr> 202</table> 203<p> 204 In table 1, each row represents an instance of a word that might not be 205 found in a standard dictionary. Each column represents some data for that word, such as the 206 locale in which it was first encountered. The column headers are column names that are stored in 207 the provider. To refer to a row's locale, you refer to its <code>locale</code> column. For 208 this provider, the <code>_ID</code> column serves as a "primary key" column that 209 the provider automatically maintains. 210</p> 211<p class="note"> 212 <strong>Note:</strong> A provider isn't required to have a primary key, and it isn't required 213 to use <code>_ID</code> as the column name of a primary key if one is present. However, 214 if you want to bind data from a provider to a {@link android.widget.ListView}, one of the 215 column names has to be <code>_ID</code>. This requirement is explained in more detail in the 216 section <a href="#DisplayResults">Displaying query results</a>. 217</p> 218<h3 id="ClientProvider">Accessing a provider</h3> 219<p> 220 An application accesses the data from a content provider with 221 a {@link android.content.ContentResolver} client object. This object has methods that call 222 identically-named methods in the provider object, an instance of one of the concrete 223 subclasses of {@link android.content.ContentProvider}. The 224 {@link android.content.ContentResolver} methods provide the basic 225 "CRUD" (create, retrieve, update, and delete) functions of persistent storage. 226</p> 227<p> 228 The {@link android.content.ContentResolver} object in the client application's 229 process and the {@link android.content.ContentProvider} object in the application that owns 230 the provider automatically handle inter-process communication. 231 {@link android.content.ContentProvider} also acts as an abstraction layer between its 232 repository of data and the external appearance of data as tables. 233</p> 234<p class="note"> 235 <strong>Note:</strong> To access a provider, your application usually has to request specific 236 permissions in its manifest file. This is described in more detail in the section 237 <a href="#Permissions">Content Provider Permissions</a> 238</p> 239<p> 240 For example, to get a list of the words and their locales from the User Dictionary Provider, 241 you call {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) 242 ContentResolver.query()}. 243 The {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) 244 query()} method calls the 245 {@link android.content.ContentProvider#query(Uri, String[], String, String[], String) 246 ContentProvider.query()} method defined by the User Dictionary Provider. The following lines 247 of code show a 248 {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) 249 ContentResolver.query()} call: 250<p> 251<pre> 252// Queries the user dictionary and returns results 253mCursor = getContentResolver().query( 254 UserDictionary.Words.CONTENT_URI, // The content URI of the words table 255 mProjection, // The columns to return for each row 256 mSelectionClause // Selection criteria 257 mSelectionArgs, // Selection criteria 258 mSortOrder); // The sort order for the returned rows 259</pre> 260<p> 261 Table 2 shows how the arguments to 262 {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) 263 query(Uri,projection,selection,selectionArgs,sortOrder)} match an SQL SELECT statement: 264</p> 265<p class="table-caption"> 266 <strong>Table 2:</strong> Query() compared to SQL query. 267</p> 268<table id="table2" style="width: 75%;"> 269 <tr> 270 <th style="width:25%" align="center" scope="col">query() argument</th> 271 <th style="width:25%" align="center" scope="col">SELECT keyword/parameter</th> 272 <th style="width:50%" align="center" scope="col">Notes</th> 273 </tr> 274 <tr> 275 <td align="center"><code>Uri</code></td> 276 <td align="center"><code>FROM <em>table_name</em></code></td> 277 <td><code>Uri</code> maps to the table in the provider named <em>table_name</em>.</td> 278 </tr> 279 <tr> 280 <td align="center"><code>projection</code></td> 281 <td align="center"><code><em>col,col,col,...</em></code></td> 282 <td> 283 <code>projection</code> is an array of columns that should be included for each row 284 retrieved. 285 </td> 286 </tr> 287 <tr> 288 <td align="center"><code>selection</code></td> 289 <td align="center"><code>WHERE <em>col</em> = <em>value</em></code></td> 290 <td><code>selection</code> specifies the criteria for selecting rows.</td> 291 </tr> 292 <tr> 293 <td align="center"><code>selectionArgs</code></td> 294 <td align="center"> 295 (No exact equivalent. Selection arguments replace <code>?</code> placeholders in the 296 selection clause.) 297 </td> 298 </tr> 299 <tr> 300 <td align="center"><code>sortOrder</code></td> 301 <td align="center"><code>ORDER BY <em>col,col,...</em></code></td> 302 <td> 303 <code>sortOrder</code> specifies the order in which rows appear in the returned 304 {@link android.database.Cursor}. 305 </td> 306 </tr> 307</table> 308<h3 id="ContentURIs">Content URIs</h3> 309<p> 310 A <strong>content URI</strong> is a URI that identifies data in a provider. Content URIs 311 include the symbolic name of the entire provider (its <strong>authority</strong>) and a 312 name that points to a table (a <strong>path</strong>). When you call 313 a client method to access a table in a provider, the content URI for the table is one of 314 the arguments. 315</p> 316<p> 317 In the preceding lines of code, the constant 318 {@link android.provider.UserDictionary.Words#CONTENT_URI} contains the content URI of 319 the user dictionary's "words" table. The {@link android.content.ContentResolver} 320 object parses out the URI's authority, and uses it to "resolve" the provider by 321 comparing the authority to a system table of known providers. The 322 {@link android.content.ContentResolver} can then dispatch the query arguments to the correct 323 provider. 324</p> 325<p> 326 The {@link android.content.ContentProvider} uses the path part of the content URI to choose the 327 table to access. A provider usually has a <strong>path</strong> for each table it exposes. 328</p> 329<p> 330 In the previous lines of code, the full URI for the "words" table is: 331</p> 332<pre> 333content://user_dictionary/words 334</pre> 335<p> 336 where the <code>user_dictionary</code> string is the provider's authority, and 337 <code>words</code> string is the table's path. The string 338 <code>content://</code> (the <strong>scheme</strong>) is always present, 339 and identifies this as a content URI. 340</p> 341<p> 342 Many providers allow you to access a single row in a table by appending an ID value 343 to the end of the URI. For example, to retrieve a row whose <code>_ID</code> is 344 <code>4</code> from user dictionary, you can use this content URI: 345</p> 346<pre> 347Uri singleUri = ContentUri.withAppendedId(UserDictionary.Words.CONTENT_URI,4); 348</pre> 349<p> 350 You often use id values when you've retrieved a set of rows and then want to update or delete 351 one of them. 352</p> 353<p class="note"> 354 <strong>Note:</strong> The {@link android.net.Uri} and {@link android.net.Uri.Builder} classes 355 contain convenience methods for constructing well-formed Uri objects from strings. The 356 {@link android.content.ContentUris} contains convenience methods for appending id values to 357 a URI. The previous snippet uses {@link android.content.ContentUris#withAppendedId(Uri, long) 358 withAppendedId()} to append an id to the UserDictionary content URI. 359</p> 360 361 362 <!-- Retrieving Data from the Provider --> 363<h2 id="SimpleQuery">Retrieving Data from the Provider</h2> 364<p> 365 This section describes how to retrieve data from a provider, using the User Dictionary Provider 366 as an example. 367</p> 368<p class="note"> 369 For the sake of clarity, the code snippets in this section call 370 {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) 371 ContentResolver.query()} on the "UI thread"". In actual code, however, you should 372 do queries asynchronously on a separate thread. One way to do this is to use the 373 {@link android.content.CursorLoader} class, which is described 374 in more detail in the <a href="{@docRoot}guide/components/loaders.html"> 375 Loaders</a> guide. Also, the lines of code are snippets only; they don't show a complete 376 application. 377</p> 378<p> 379 To retrieve data from a provider, follow these basic steps: 380</p> 381<ol> 382 <li> 383 Request the read access permission for the provider. 384 </li> 385 <li> 386 Define the code that sends a query to the provider. 387 </li> 388</ol> 389<h3 id="RequestPermissions">Requesting read access permission</h3> 390<p> 391 To retrieve data from a provider, your application needs "read access permission" for the 392 provider. You can't request this permission at run-time; instead, you have to specify that 393 you need this permission in your manifest, using the 394 <code><a href="{@docRoot}guide/topics/manifest/uses-permission-element.html"> 395 <uses-permission></a></code> element and the exact permission name defined by the 396 provider. When you specify this element in your manifest, you are in effect "requesting" this 397 permission for your application. When users install your application, they implicitly grant 398 this request. 399</p> 400<p> 401 To find the exact name of the read access permission for the provider you're using, as well 402 as the names for other access permissions used by the provider, look in the provider's 403 documentation. 404</p> 405<p> 406 The role of permissions in accessing providers is described in more detail in the section 407 <a href="#Permissions">Content Provider Permissions</a>. 408</p> 409<p> 410 The User Dictionary Provider defines the permission 411 <code>android.permission.READ_USER_DICTIONARY</code> in its manifest file, so an 412 application that wants to read from the provider must request this permission. 413</p> 414<!-- Constructing the query --> 415<h3 id="Query">Constructing the query</h3> 416<p> 417 The next step in retrieving data a provider is to construct a query. This first snippet 418 defines some variables for accessing the User Dictionary Provider: 419</p> 420<pre class="prettyprint"> 421 422// A "projection" defines the columns that will be returned for each row 423String[] mProjection = 424{ 425 UserDictionary.Words._ID, // Contract class constant for the _ID column name 426 UserDictionary.Words.WORD, // Contract class constant for the word column name 427 UserDictionary.Words.LOCALE // Contract class constant for the locale column name 428}; 429 430// Defines a string to contain the selection clause 431String mSelectionClause = null; 432 433// Initializes an array to contain selection arguments 434String[] mSelectionArgs = {""}; 435 436</pre> 437<p> 438 The next snippet shows how to use 439 {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) 440 ContentResolver.query()}, using the User Dictionary Provider as an example. 441 A provider client query is similar to an SQL query, and it contains a set of columns to return, 442 a set of selection criteria, and a sort order. 443</p> 444<p> 445 The set of columns that the query should return is called a <strong>projection</strong> 446 (the variable <code>mProjection</code>). 447</p> 448<p> 449 The expression that specifies the rows to retrieve is split into a selection clause and 450 selection arguments. The selection clause is a combination of logical and Boolean expressions, 451 column names, and values (the variable <code>mSelection</code>). If you specify the replaceable 452 parameter <code>?</code> instead of a value, the query method retrieves the value from the 453 selection arguments array (the variable <code>mSelectionArgs</code>). 454</p> 455<p> 456 In the next snippet, if the user doesn't enter a word, the selection clause is set to 457 <code>null</code>, and the query returns all the words in the provider. If the user enters 458 a word, the selection clause is set to <code>UserDictionary.Words.Word + " = ?"</code> and 459 the first element of selection arguments array is set to the word the user enters. 460</p> 461<pre class="prettyprint"> 462/* 463 * This defines a one-element String array to contain the selection argument. 464 */ 465String[] mSelectionArgs = {""}; 466 467// Gets a word from the UI 468mSearchString = mSearchWord.getText().toString(); 469 470// Remember to insert code here to check for invalid or malicious input. 471 472// If the word is the empty string, gets everything 473if (TextUtils.isEmpty(mSearchString)) { 474 // Setting the selection clause to null will return all words 475 mSelectionClause = null; 476 mSelectionArgs[0] = ""; 477 478} else { 479 // Constructs a selection clause that matches the word that the user entered. 480 mSelectionClause = " = ?"; 481 482 // Moves the user's input string to the selection arguments. 483 mSelectionArgs[0] = mSearchString; 484 485} 486 487// Does a query against the table and returns a Cursor object 488mCursor = getContentResolver().query( 489 UserDictionary.Words.CONTENT_URI, // The content URI of the words table 490 mProjection, // The columns to return for each row 491 mSelectionClause // Either null, or the word the user entered 492 mSelectionArgs, // Either empty, or the string the user entered 493 mSortOrder); // The sort order for the returned rows 494 495// Some providers return null if an error occurs, others throw an exception 496if (null == mCursor) { 497 /* 498 * Insert code here to handle the error. Be sure not to use the cursor! You may want to 499 * call android.util.Log.e() to log this error. 500 * 501 */ 502// If the Cursor is empty, the provider found no matches 503} else if (mCursor.getCount() < 1) { 504 505 /* 506 * Insert code here to notify the user that the search was unsuccessful. This isn't necessarily 507 * an error. You may want to offer the user the option to insert a new row, or re-type the 508 * search term. 509 */ 510 511} else { 512 // Insert code here to do something with the results 513 514} 515</pre> 516<p> 517 This query is analogous to the SQL statement: 518</p> 519<pre> 520SELECT _ID, word, frequency, locale FROM words WHERE word = <userinput> ORDER BY word ASC; 521</pre> 522<p> 523 In this SQL statement, the actual column names are used instead of contract class constants. 524</p> 525<h4 id="Injection">Protecting against malicious input</h4> 526<p> 527 If the data managed by the content provider is in an SQL database, including external untrusted 528 data into raw SQL statements can lead to SQL injection. 529</p> 530<p> 531 Consider this selection clause: 532</p> 533<pre> 534// Constructs a selection clause by concatenating the user's input to the column name 535String mSelectionClause = "var = " + mUserInput; 536</pre> 537<p> 538 If you do this, you're allowing the user to concatenate malicious SQL onto your SQL statement. 539 For example, the user could enter "nothing; DROP TABLE *;" for <code>mUserInput</code>, which 540 would result in the selection clause <code>var = nothing; DROP TABLE *;</code>. Since the 541 selection clause is treated as an SQL statement, this might cause the provider to erase all of 542 the tables in the underlying SQLite database (unless the provider is set up to catch 543 <a href="http://en.wikipedia.org/wiki/SQL_injection">SQL injection</a> attempts). 544</p> 545<p> 546 To avoid this problem, use a selection clause that uses <code>?</code> as a replaceable 547 parameter and a separate array of selection arguments. When you do this, the user input 548 is bound directly to the query rather than being interpreted as part of an SQL statement. 549 Because it's not treated as SQL, the user input can't inject malicious SQL. Instead of using 550 concatenation to include the user input, use this selection clause: 551</p> 552<pre> 553// Constructs a selection clause with a replaceable parameter 554String mSelectionClause = "var = ?"; 555</pre> 556<p> 557 Set up the array of selection arguments like this: 558</p> 559<pre> 560// Defines an array to contain the selection arguments 561String[] selectionArgs = {""}; 562</pre> 563<p> 564 Put a value in the selection arguments array like this: 565</p> 566<pre> 567// Sets the selection argument to the user's input 568selectionArgs[0] = mUserInput; 569</pre> 570<p> 571 A selection clause that uses <code>?</code> as a replaceable parameter and an array of 572 selection arguments array are preferred way to specify a selection, even if the provider isn't 573 based on an SQL database. 574</p> 575<!-- Displaying the results --> 576<h3 id="DisplayResults">Displaying query results</h3> 577<p> 578 The {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) 579 ContentResolver.query()} client method always returns a {@link android.database.Cursor} 580 containing the columns specified by the query's projection for the rows that match the query's 581 selection criteria. A {@link android.database.Cursor} object provides random read access to the 582 rows and columns it contains. Using {@link android.database.Cursor} methods, 583 you can iterate over the rows in the results, determine the data type of each column, get the 584 data out of a column, and examine other properties of the results. Some 585 {@link android.database.Cursor} implementations automatically update the object when the 586 provider's data changes, or trigger methods in an observer object when the 587 {@link android.database.Cursor} changes, or both. 588</p> 589<p class="note"> 590 <strong>Note:</strong> A provider may restrict access to columns based on the nature of the 591 object making the query. For example, the Contacts Provider restricts access for some columns to 592 sync adapters, so it won't return them to an activity or service. 593</p> 594<p> 595 If no rows match the selection criteria, the provider 596 returns a {@link android.database.Cursor} object for which 597 {@link android.database.Cursor#getCount() Cursor.getCount()} is 0 (an empty cursor). 598</p> 599<p> 600 If an internal error occurs, the results of the query depend on the particular provider. It may 601 choose to return <code>null</code>, or it may throw an {@link java.lang.Exception}. 602</p> 603<p> 604 Since a {@link android.database.Cursor} is a "list" of rows, a good way to display the 605 contents of a {@link android.database.Cursor} is to link it to a {@link android.widget.ListView} 606 via a {@link android.widget.SimpleCursorAdapter}. 607</p> 608<p> 609 The following snippet continues the code from the previous snippet. It creates a 610 {@link android.widget.SimpleCursorAdapter} object containing the {@link android.database.Cursor} 611 retrieved by the query, and sets this object to be the adapter for a 612 {@link android.widget.ListView}: 613</p> 614<pre class="prettyprint"> 615// Defines a list of columns to retrieve from the Cursor and load into an output row 616String[] mWordListColumns = 617{ 618 UserDictionary.Words.WORD, // Contract class constant containing the word column name 619 UserDictionary.Words.LOCALE // Contract class constant containing the locale column name 620}; 621 622// Defines a list of View IDs that will receive the Cursor columns for each row 623int[] mWordListItems = { R.id.dictWord, R.id.locale}; 624 625// Creates a new SimpleCursorAdapter 626mCursorAdapter = new SimpleCursorAdapter( 627 getApplicationContext(), // The application's Context object 628 R.layout.wordlistrow, // A layout in XML for one row in the ListView 629 mCursor, // The result from the query 630 mWordListColumns, // A string array of column names in the cursor 631 mWordListItems, // An integer array of view IDs in the row layout 632 0); // Flags (usually none are needed) 633 634// Sets the adapter for the ListView 635mWordList.setAdapter(mCursorAdapter); 636</pre> 637<p class="note"> 638 <strong>Note:</strong> To back a {@link android.widget.ListView} with a 639 {@link android.database.Cursor}, the cursor must contain a column named <code>_ID</code>. 640 Because of this, the query shown previously retrieves the <code>_ID</code> column for the 641 "words" table, even though the {@link android.widget.ListView} doesn't display it. 642 This restriction also explains why most providers have a <code>_ID</code> column for each of 643 their tables. 644</p> 645 646 <!-- Getting data from query results --> 647<h3 id="GettingResults">Getting data from query results</h3> 648<p> 649 Rather than simply displaying query results, you can use them for other tasks. For 650 example, you can retrieve spellings from the user dictionary and then look them up in 651 other providers. To do this, you iterate over the rows in the {@link android.database.Cursor}: 652</p> 653<pre class="prettyprint"> 654 655// Determine the column index of the column named "word" 656int index = mCursor.getColumnIndex(UserDictionary.Words.WORD); 657 658/* 659 * Only executes if the cursor is valid. The User Dictionary Provider returns null if 660 * an internal error occurs. Other providers may throw an Exception instead of returning null. 661 */ 662 663if (mCursor != null) { 664 /* 665 * Moves to the next row in the cursor. Before the first movement in the cursor, the 666 * "row pointer" is -1, and if you try to retrieve data at that position you will get an 667 * exception. 668 */ 669 while (mCursor.moveToNext()) { 670 671 // Gets the value from the column. 672 newWord = mCursor.getString(index); 673 674 // Insert code here to process the retrieved word. 675 676 ... 677 678 // end of while loop 679 } 680} else { 681 682 // Insert code here to report an error if the cursor is null or the provider threw an exception. 683} 684</pre> 685<p> 686 {@link android.database.Cursor} implementations contain several "get" methods for 687 retrieving different types of data from the object. For example, the previous snippet 688 uses {@link android.database.Cursor#getString(int) getString()}. They also have a 689 {@link android.database.Cursor#getType(int) getType()} method that returns a value indicating 690 the data type of the column. 691</p> 692 693 694 <!-- Requesting permissions --> 695<h2 id="Permissions">Content Provider Permissions</h2> 696<p> 697 A provider's application can specify permissions that other applications must have in order to 698 access the provider's data. These permissions ensure that the user knows what data 699 an application will try to access. Based on the provider's requirements, other applications 700 request the permissions they need in order to access the provider. End users see the requested 701 permissions when they install the application. 702</p> 703<p> 704 If a provider's application doesn't specify any permissions, then other applications have no 705 access to the provider's data. However, components in the provider's application always have 706 full read and write access, regardless of the specified permissions. 707</p> 708<p> 709 As noted previously, the User Dictionary Provider requires the 710 <code>android.permission.READ_USER_DICTIONARY</code> permission to retrieve data from it. 711 The provider has the separate <code>android.permission.WRITE_USER_DICTIONARY</code> 712 permission for inserting, updating, or deleting data. 713</p> 714<p> 715 To get the permissions needed to access a provider, an application requests them with a 716 <code><a href="{@docRoot}guide/topics/manifest/uses-permission-element.html"> 717 <uses-permission></a></code> element in its manifest file. 718 When the Android Package Manager installs the application, a user must approve all of the 719 permissions the application requests. If the user approves all of them, Package Manager 720 continues the installation; if the user doesn't approve them, Package Manager 721 aborts the installation. 722</p> 723<p> 724 The following 725 <code><a href="{@docRoot}guide/topics/manifest/uses-permission-element.html"> 726 <uses-permission></a></code> element requests read access to the User Dictionary Provider: 727</p> 728<pre> 729 <uses-permission android:name="android.permission.READ_USER_DICTIONARY"> 730</pre> 731<p> 732 The impact of permissions on provider access is explained in more detail in the 733 <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a> guide. 734</p> 735 736 737<!-- Inserting, Updating, and Deleting Data --> 738<h2 id="Modifications">Inserting, Updating, and Deleting Data</h2> 739<p> 740 In the same way that you retrieve data from a provider, you also use the interaction between 741 a provider client and the provider's {@link android.content.ContentProvider} to modify data. 742 You call a method of {@link android.content.ContentResolver} with arguments that are passed to 743 the corresponding method of {@link android.content.ContentProvider}. The provider and provider 744 client automatically handle security and inter-process communication. 745</p> 746<h3 id="Inserting">Inserting data</h3> 747<p> 748 To insert data into a provider, you call the 749 {@link android.content.ContentResolver#insert(Uri,ContentValues) ContentResolver.insert()} 750 method. This method inserts a new row into the provider and returns a content URI for that row. 751 This snippet shows how to insert a new word into the User Dictionary Provider: 752</p> 753<pre class="prettyprint"> 754// Defines a new Uri object that receives the result of the insertion 755Uri mNewUri; 756 757... 758 759// Defines an object to contain the new values to insert 760ContentValues mNewValues = new ContentValues(); 761 762/* 763 * Sets the values of each column and inserts the word. The arguments to the "put" 764 * method are "column name" and "value" 765 */ 766mNewValues.put(UserDictionary.Words.APP_ID, "example.user"); 767mNewValues.put(UserDictionary.Words.LOCALE, "en_US"); 768mNewValues.put(UserDictionary.Words.WORD, "insert"); 769mNewValues.put(UserDictionary.Words.FREQUENCY, "100"); 770 771mNewUri = getContentResolver().insert( 772 UserDictionary.Word.CONTENT_URI, // the user dictionary content URI 773 mNewValues // the values to insert 774); 775</pre> 776<p> 777 The data for the new row goes into a single {@link android.content.ContentValues} object, which 778 is similar in form to a one-row cursor. The columns in this object don't need to have the 779 same data type, and if you don't want to specify a value at all, you can set a column 780 to <code>null</code> using {@link android.content.ContentValues#putNull(String) 781 ContentValues.putNull()}. 782</p> 783<p> 784 The snippet doesn't add the <code>_ID</code> column, because this column is maintained 785 automatically. The provider assigns a unique value of <code>_ID</code> to every row that is 786 added. Providers usually use this value as the table's primary key. 787</p> 788<p> 789 The content URI returned in <code>newUri</code> identifies the newly-added row, with 790 the following format: 791</p> 792<pre> 793content://user_dictionary/words/<id_value> 794</pre> 795<p> 796 The <code><id_value></code> is the contents of <code>_ID</code> for the new row. 797 Most providers can detect this form of content URI automatically and then perform the requested 798 operation on that particular row. 799</p> 800<p> 801 To get the value of <code>_ID</code> from the returned {@link android.net.Uri}, call 802 {@link android.content.ContentUris#parseId(Uri) ContentUris.parseId()}. 803</p> 804<h3 id="Updating">Updating data</h3> 805<p> 806 To update a row, you use a {@link android.content.ContentValues} object with the updated 807 values just as you do with an insertion, and selection criteria just as you do with a query. 808 The client method you use is 809 {@link android.content.ContentResolver#update(Uri, ContentValues, String, String[]) 810 ContentResolver.update()}. You only need to add values to the 811 {@link android.content.ContentValues} object for columns you're updating. If you want to clear 812 the contents of a column, set the value to <code>null</code>. 813</p> 814<p> 815 The following snippet changes all the rows whose locale has the language "en" to a 816 have a locale of <code>null</code>. The return value is the number of rows that were updated: 817</p> 818<pre> 819// Defines an object to contain the updated values 820ContentValues mUpdateValues = new ContentValues(); 821 822// Defines selection criteria for the rows you want to update 823String mSelectionClause = UserDictionary.Words.LOCALE + "LIKE ?"; 824String[] mSelectionArgs = {"en_%"}; 825 826// Defines a variable to contain the number of updated rows 827int mRowsUpdated = 0; 828 829... 830 831/* 832 * Sets the updated value and updates the selected words. 833 */ 834mUpdateValues.putNull(UserDictionary.Words.LOCALE); 835 836mRowsUpdated = getContentResolver().update( 837 UserDictionary.Words.CONTENT_URI, // the user dictionary content URI 838 mUpdateValues // the columns to update 839 mSelectionClause // the column to select on 840 mSelectionArgs // the value to compare to 841); 842</pre> 843<p> 844 You should also sanitize user input when you call 845 {@link android.content.ContentResolver#update(Uri, ContentValues, String, String[]) 846 ContentResolver.update()}. To learn more about this, read the section 847 <a href="#Injection">Protecting against malicious input</a>. 848</p> 849<h3 id="Deleting">Deleting data</h3> 850<p> 851 Deleting rows is similar to retrieving row data: you specify selection criteria for the rows 852 you want to delete and the client method returns the number of deleted rows. 853 The following snippet deletes rows whose appid matches "user". The method returns the 854 number of deleted rows. 855</p> 856<pre> 857 858// Defines selection criteria for the rows you want to delete 859String mSelectionClause = UserDictionary.Words.APP_ID + " LIKE ?"; 860String[] mSelectionArgs = {"user"}; 861 862// Defines a variable to contain the number of rows deleted 863int mRowsDeleted = 0; 864 865... 866 867// Deletes the words that match the selection criteria 868mRowsDeleted = getContentResolver().delete( 869 UserDictionary.Words.CONTENT_URI, // the user dictionary content URI 870 mSelectionClause // the column to select on 871 mSelectionArgs // the value to compare to 872); 873</pre> 874<p> 875 You should also sanitize user input when you call 876 {@link android.content.ContentResolver#delete(Uri, String, String[]) 877 ContentResolver.delete()}. To learn more about this, read the section 878 <a href="#Injection">Protecting against malicious input</a>. 879</p> 880<!-- Provider Data Types --> 881<h2 id="DataTypes">Provider Data Types</h2> 882<p> 883 Content providers can offer many different data types. The User Dictionary Provider offers only 884 text, but providers can also offer the following formats: 885</p> 886 <ul> 887 <li> 888 integer 889 </li> 890 <li> 891 long integer (long) 892 </li> 893 <li> 894 floating point 895 </li> 896 <li> 897 long floating point (double) 898 </li> 899 </ul> 900<p> 901 Another data type that providers often use is Binary Large OBject (BLOB) implemented as a 902 64KB byte array. You can see the available data types by looking at the 903 {@link android.database.Cursor} class "get" methods. 904</p> 905<p> 906 The data type for each column in a provider is usually listed in its documentation. 907 The data types for the User Dictionary Provider are listed in the reference documentation 908 for its contract class {@link android.provider.UserDictionary.Words} (contract classes are 909 described in the section <a href="#ContractClasses">Contract Classes</a>). 910 You can also determine the data type by calling {@link android.database.Cursor#getType(int) 911 Cursor.getType()}. 912</p> 913<p> 914 Providers also maintain MIME data type information for each content URI they define. You can 915 use the MIME type information to find out if your application can handle data that the 916 provider offers, or to choose a type of handling based on the MIME type. You usually need the 917 MIME type when you are working with a provider that contains complex 918 data structures or files. For example, the {@link android.provider.ContactsContract.Data} 919 table in the Contacts Provider uses MIME types to label the type of contact data stored in each 920 row. To get the MIME type corresponding to a content URI, call 921 {@link android.content.ContentResolver#getType(Uri) ContentResolver.getType()}. 922</p> 923<p> 924 The section <a href="#MIMETypeReference">MIME Type Reference</a> describes the 925 syntax of both standard and custom MIME types. 926</p> 927 928 929<!-- Alternative Forms of Provider Access --> 930<h2 id="AltForms">Alternative Forms of Provider Access</h2> 931<p> 932 Three alternative forms of provider access are important in application development: 933</p> 934<ul> 935 <li> 936 <a href="#Batch">Batch access</a>: You can create a batch of access calls with methods in 937 the {@link android.content.ContentProviderOperation} class, and then apply them with 938 {@link android.content.ContentResolver#applyBatch(String, ArrayList) 939 ContentResolver.applyBatch()}. 940 </li> 941 <li> 942 Asynchronous queries: You should do queries in a separate thread. One way to do this is to 943 use a {@link android.content.CursorLoader} object. The examples in the 944 <a href="{@docRoot}guide/components/loaders.html">Loaders</a> guide demonstrate 945 how to do this. 946 </li> 947 <li> 948 <a href="#Intents">Data access via intents</a>: Although you can't send an intent 949 directly to a provider, you can send an intent to the provider's application, which is 950 usually the best-equipped to modify the provider's data. 951 </li> 952</ul> 953<p> 954 Batch access and modification via intents are described in the following sections. 955</p> 956<h3 id="Batch">Batch access</h3> 957<p> 958 Batch access to a provider is useful for inserting a large number of rows, or for inserting 959 rows in multiple tables in the same method call, or in general for performing a set of 960 operations across process boundaries as a transaction (an atomic operation). 961</p> 962<p> 963 To access a provider in "batch mode", 964 you create an array of {@link android.content.ContentProviderOperation} objects and then 965 dispatch them to a content provider with 966 {@link android.content.ContentResolver#applyBatch(String, ArrayList) 967 ContentResolver.applyBatch()}. You pass the content provider's <em>authority</em> to this 968 method, rather than a particular content URI, which allows each 969 {@link android.content.ContentProviderOperation} object in the array to work against a 970 different table. A call to {@link android.content.ContentResolver#applyBatch(String, ArrayList) 971 ContentResolver.applyBatch()} returns an array of results. 972</p> 973<p> 974 The description of the {@link android.provider.ContactsContract.RawContacts} contract class 975 includes a code snippet that demonstrates batch insertion. The 976 <a href="{@docRoot}resources/samples/ContactManager/index.html">Contact Manager</a> 977 sample application contains an example of batch access in its <code>ContactAdder.java</code> 978 source file. 979</p> 980<div class="sidebox-wrapper"> 981<div class="sidebox"> 982<h2>Displaying data using a helper app</h2> 983<p> 984 If your application <em>does</em> have access permissions, you still may want to use an 985 intent to display data in another application. For example, the Calendar application accepts an 986 {@link android.content.Intent#ACTION_VIEW} intent, which displays a particular date or event. 987 This allows you to display calendar information without having to create your own UI. 988 To learn more about this feature, see the 989 <a href="{@docRoot}guide/topics/providers/calendar-provider.html">Calendar Provider</a> guide. 990</p> 991<p> 992 The application to which you send the intent doesn't have to be the application 993 associated with the provider. For example, you can retrieve a contact from the 994 Contact Provider, then send an {@link android.content.Intent#ACTION_VIEW} intent 995 containing the content URI for the contact's image to an image viewer. 996</p> 997</div> 998</div> 999<h3 id="Intents">Data access via intents</h3> 1000<p> 1001 Intents can provide indirect access to a content provider. You allow the user to access 1002 data in a provider even if your application doesn't have access permissions, either by 1003 getting a result intent back from an application that has permissions, or by activating an 1004 application that has permissions and letting the user do work in it. 1005</p> 1006<h4>Getting access with temporary permissions</h4> 1007<p> 1008 You can access data in a content provider, even if you don't have the proper access 1009 permissions, by sending an intent to an application that does have the permissions and 1010 receiving back a result intent containing "URI" permissions. 1011 These are permissions for a specific content URI that last until the activity that receives 1012 them is finished. The application that has permanent permissions grants temporary 1013 permissions by setting a flag in the result intent: 1014</p> 1015<ul> 1016 <li> 1017 <strong>Read permission:</strong> 1018 {@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION} 1019 </li> 1020 <li> 1021 <strong>Write permission:</strong> 1022 {@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION} 1023 </li> 1024</ul> 1025<p class="note"> 1026 <strong>Note:</strong> These flags don't give general read or write access to the provider 1027 whose authority is contained in the content URI. The access is only for the URI itself. 1028</p> 1029<p> 1030 A provider defines URI permissions for content URIs in its manifest, using the 1031 <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn"> 1032 android:grantUriPermission</a></code> 1033 attribute of the 1034 {@code <a href="guide/topics/manifest/provider-element.html"><provider></a>} 1035 element, as well as the 1036 {@code <a href="guide/topics/manifest/grant-uri-permission-element.html"> 1037 <grant-uri-permission></a>} child element of the 1038 {@code <a href="guide/topics/manifest/provider-element.html"><provider></a>} 1039 element. The URI permissions mechanism is explained in more detail in the 1040 <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a> guide, 1041 in the section "URI Permissions". 1042</p> 1043<p> 1044 For example, you can retrieve data for a contact in the Contacts Provider, even if you don't 1045 have the {@link android.Manifest.permission#READ_CONTACTS} permission. You might want to do 1046 this in an application that sends e-greetings to a contact on his or her birthday. Instead of 1047 requesting {@link android.Manifest.permission#READ_CONTACTS}, which gives you access to all of 1048 the user's contacts and all of their information, you prefer to let the user control which 1049 contacts are used by your application. To do this, you use the following process: 1050</p> 1051<ol> 1052 <li> 1053 Your application sends an intent containing the action 1054 {@link android.content.Intent#ACTION_PICK} and the "contacts" MIME type 1055 {@link android.provider.ContactsContract.RawContacts#CONTENT_ITEM_TYPE}, using the 1056 method {@link android.app.Activity#startActivityForResult(Intent, int) 1057 startActivityForResult()}. 1058 </li> 1059 <li> 1060 Because this intent matches the intent filter for the 1061 People app's "selection" activity, the activity will come to the foreground. 1062 </li> 1063 <li> 1064 In the selection activity, the user selects a 1065 contact to update. When this happens, the selection activity calls 1066 {@link android.app.Activity#setResult(int, Intent) setResult(resultcode, intent)} 1067 to set up a intent to give back to your application. The intent contains the content URI 1068 of the contact the user selected, and the "extras" flags 1069 {@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION}. These flags grant URI 1070 permission to your app to read data for the contact pointed to by the 1071 content URI. The selection activity then calls {@link android.app.Activity#finish()} to 1072 return control to your application. 1073 </li> 1074 <li> 1075 Your activity returns to the foreground, and the system calls your activity's 1076 {@link android.app.Activity#onActivityResult(int, int, Intent) onActivityResult()} 1077 method. This method receives the result intent created by the selection activity in 1078 the People app. 1079 </li> 1080 <li> 1081 With the content URI from the result intent, you can read the contact's data 1082 from the Contacts Provider, even though you didn't request permanent read access permission 1083 to the provider in your manifest. You can then get the contact's birthday information 1084 or his or her email address and then send the e-greeting. 1085 </li> 1086</ol> 1087<h4>Using another application</h4> 1088<p> 1089 A simple way to allow the user to modify data to which you don't have access permissions is to 1090 activate an application that has permissions and let the user do the work there. 1091</p> 1092<p> 1093 For example, the Calendar application accepts an 1094 {@link android.content.Intent#ACTION_INSERT} intent, which allows you to activate the 1095 application's insert UI. You can pass "extras" data in this intent, which the application 1096 uses to pre-populate the UI. Because recurring events have a complex syntax, the preferred 1097 way of inserting events into the Calendar Provider is to activate the Calendar app with an 1098 {@link android.content.Intent#ACTION_INSERT} and then let the user insert the event there. 1099</p> 1100<!-- Contract Classes --> 1101<h2 id="ContractClasses">Contract Classes</h2> 1102<p> 1103 A contract class defines constants that help applications work with the content URIs, column 1104 names, intent actions, and other features of a content provider. Contract classes are not 1105 included automatically with a provider; the provider's developer has to define them and then 1106 make them available to other developers. Many of the providers included with the Android 1107 platform have corresponding contract classes in the package {@link android.provider}. 1108</p> 1109<p> 1110 For example, the User Dictionary Provider has a contract class 1111 {@link android.provider.UserDictionary} containing content URI and column name constants. The 1112 content URI for the "words" table is defined in the constant 1113 {@link android.provider.UserDictionary.Words#CONTENT_URI UserDictionary.Words.CONTENT_URI}. 1114 The {@link android.provider.UserDictionary.Words} class also contains column name constants, 1115 which are used in the example snippets in this guide. For example, a query projection can be 1116 defined as: 1117</p> 1118<pre> 1119String[] mProjection = 1120{ 1121 UserDictionary.Words._ID, 1122 UserDictionary.Words.WORD, 1123 UserDictionary.Words.LOCALE 1124}; 1125</pre> 1126<p> 1127 Another contract class is {@link android.provider.ContactsContract} for the Contacts Provider. 1128 The reference documentation for this class includes example code snippets. One of its 1129 subclasses, {@link android.provider.ContactsContract.Intents.Insert}, is a contract 1130 class that contains constants for intents and intent data. 1131</p> 1132 1133 1134<!-- MIME Type Reference --> 1135<h2 id="MIMETypeReference">MIME Type Reference</h2> 1136<p> 1137 Content providers can return standard MIME media types, or custom MIME type strings, or both. 1138</p> 1139<p> 1140 MIME types have the format 1141</p> 1142<pre> 1143<em>type</em>/<em>subtype</em> 1144</pre> 1145<p> 1146 For example, the well-known MIME type <code>text/html</code> has the <code>text</code> type and 1147 the <code>html</code> subtype. If the provider returns this type for a URI, it means that a 1148 query using that URI will return text containing HTML tags. 1149</p> 1150<p> 1151 Custom MIME type strings, also called "vendor-specific" MIME types, have more 1152 complex <em>type</em> and <em>subtype</em> values. The <em>type</em> value is always 1153</p> 1154<pre> 1155vnd.android.cursor.<strong>dir</strong> 1156</pre> 1157<p> 1158 for multiple rows, or 1159</p> 1160<pre> 1161vnd.android.cursor.<strong>item</strong> 1162</pre> 1163<p> 1164 for a single row. 1165</p> 1166<p> 1167 The <em>subtype</em> is provider-specific. The Android built-in providers usually have a simple 1168 subtype. For example, the when the Contacts application creates a row for a telephone number, 1169 it sets the following MIME type in the row: 1170</p> 1171<pre> 1172vnd.android.cursor.item/phone_v2 1173</pre> 1174<p> 1175 Notice that the subtype value is simply <code>phone_v2</code>. 1176</p> 1177<p> 1178 Other provider developers may create their own pattern of subtypes based on the provider's 1179 authority and table names. For example, consider a provider that contains train timetables. 1180 The provider's authority is <code>com.example.trains</code>, and it contains the tables 1181 Line1, Line2, and Line3. In response to the content URI 1182</p> 1183<p> 1184<pre> 1185content://com.example.trains/Line1 1186</pre> 1187<p> 1188 for table Line1, the provider returns the MIME type 1189</p> 1190<pre> 1191vnd.android.cursor.<strong>dir</strong>/vnd.example.line1 1192</pre> 1193<p> 1194 In response to the content URI 1195</p> 1196<pre> 1197content://com.example.trains/Line2/5 1198</pre> 1199<p> 1200 for row 5 in table Line2, the provider returns the MIME type 1201</p> 1202<pre> 1203vnd.android.cursor.<strong>item</strong>/vnd.example.line2 1204</pre> 1205<p> 1206 Most content providers define contract class constants for the MIME types they use. The 1207 Contacts Provider contract class {@link android.provider.ContactsContract.RawContacts}, 1208 for example, defines the constant 1209 {@link android.provider.ContactsContract.RawContacts#CONTENT_ITEM_TYPE} for the MIME type of 1210 a single raw contact row. 1211</p> 1212<p> 1213 Content URIs for single rows are described in the section 1214 <a href="#ContentURIs">Content URIs</a>. 1215</p> 1216