[1].Content providers are the standard interface that connects data in one process with code running in another process.
[2].Note: A provider isn't required to have a primary key, and it isn't required to use _ID
as the column name of a primary key if one is present. However, if you want to bind data from a provider to a ListView
, one of the column names has to be _ID
.
[3].An application accesses the data from a content provider with a ContentResolver
client object. This object has methods that call identically-named methods in the provider object, an instance of one of the concrete subclasses of ContentProvider
. The ContentResolver
object in the client application's process and the ContentProvider
object in the application that owns the provider automatically handle inter-process communication. ContentProvider
also acts as an abstraction layer between its repository of data and the external appearance of data as tables.
[4].
content://user_dictionary/wordsThe
ContentResolver
object parses out the URI's authority
, and uses it to "resolve" the provider by comparing the authority to a system table of known providers. The ContentResolver
can then dispatch the query arguments to the correct provider.
where the user_dictionary
string is the provider's authority, and words
string is the table's path. The string content://
(the scheme) is always present, and identifies this as a content URI.
[5].Note: The Uri
and Uri.Builder
classes contain convenience methods for constructing well-formed Uri objects from strings. The ContentUris
contains convenience methods for appending id values to a URI. The previous snippet uses withAppendedId()
to append an id to the UserDictionary content URI.
[6].
To retrieve data from a provider, follow these basic steps:
- Request the read access permission for the provider.
- Define the code that sends a query to the provider.
ListView
with a
Cursor
, the cursor must contain a column named
_ID
. Because of this, the query shown previously retrieves the
_ID
column for the "words" table, even though the
ListView
doesn't display it. This restriction also explains why most providers have a
_ID
column for each of their tables.
* "row pointer" is -1, and if you try to retrieve data at that position you will get an
* exception.
if (mCursor != null) {
/*
* Moves to the next row in the cursor. Before the first movement in the cursor, the
* "row pointer" is -1, and if you try to retrieve data at that position you will get an
* exception.
*/
while (mCursor.moveToNext()) {
// Gets the value from the column.
newWord = mCursor.getString(index);
// Insert code here to process the retrieved word.
...
// end of while loop
}
}
Cursor
class "get" methods.