Content Provider Content Resolver Cursor Content Provider Basics - - PowerPoint PPT Presentation
Content Provider Content Resolver Cursor Content Provider Basics - - PowerPoint PPT Presentation
Content Provider Content Resolver Cursor Content Provider Basics Content providers is one of Androids core components that enables you to access data of other applications where data is stored in databases or flat files. SQLite
Content Resolver
Cursor
Content Provider Basics
- Content providers is one of Android’s core components that enables you
to access data of other applications where data is stored in databases or flat files.
- SQLite databases can only be used by the app that created it. However
you can choose to share the database with other apps by content provider to manage access to this shared database.
- You’ll need a content provider if you want to allow other apps to access
your database and if you want to perform custom search suggestions in your own app.
- Content providers support the four basic operations, normally called
CRUD-operations. With content providers those objects simply represent data – most often a record (tuple) of a database – but they could also be a photo on your SD-card or a video on the web.
- Android provides some standard content providers to access contacts,
media files, preferences and so on.
The standard content providers of Android Provider Since Usage Browser SDK 1 Manages your web-searches, bookmarks and browsing-history. CalendarContract SDK 14 Manages the calendars on the user’s device. CallLog SDK 1 Keeps track of your call history. Contacts SDK 1 The old and deprecated content provider for managing contacts. You should only use this provider if you need to support an SDK prior to SDK 5! ContactsContract SDK 5 Deals with all aspects of contact management. Supersedes the Contacts-content provider. MediaStore SDK 1 The content provider responsible for all your media files like music, video and pictures. Settings SDK 1 Manages all global settings of your device. UserDictionary SDK 3 Keeps track of words you add to the default dictionary.
Content resolver and content provider
- You create a content provider in the app that creates the
- database. This allows other apps to use the database.
- Any app wanting to use the database must use a content
resolver to do so.
- The Content Resolver communicates with the Content
Provider
Example to search the Contacts database for a friend’s email address
- Ask the content resolver to look for the email address. The
content resolver sends a request to the content provider to search for the email address.
- The Android system looks for the correct content provider and sends the
request to it.
- The provider finds the address and returns it to the content resolver.
- The content resolver includes methods that you use for database queries
and transactions. These methods correspond with the methods included in the content provider:
- query() – to search for data in the database
- insert() – to add data in the database
- delete() – to delete data in the database
- update() – to update data in the database
- getType() – returns the MIME type of the data in the database
Content URIs
- You use content URI to identify data in a content provider. This is the address
that you pass to the content resolver when you want to access a database created in another app. content://authority/optionalPath/optionalId four parts: The scheme to use, an authority, an optional path and an optional id.
- The scheme for content providers is always “content”. The colon and double-
slash “://” are a fixed part of the URI-RFC and separate the scheme from the authority.
- Authorities: complete address of the provider, unique for each content
provider: package name plus the name of your content provider name
- The optional path: table name, is used to distinguish the kinds of data your
content provider offers. The content provider for Android’s media store, for example, distinguishes between audio files, video files and images using different paths for each of these types of media.
- The last element is the optional id, which must be numeric. The id is used
whenever you want to access a single record (row) (e.g. a specific video file).
Content URI Examples
- <scheme><AUTHORITY><path/ID>
- content://com.example.slqitemodule.
MyContentProvider/MyContacts_table //You’d use this address to query the whole table
- content://com.example.slqitemodule.
MyContentProvider/MyContacts_table/12 //You’d use this address to query row 12 in the table
Declare the provider in the AndroidManifest.xml
- Register content provider in the manifest file
- The Android system now includes this provider in its
list of Content Providers
- authorities – consists of the <package name >.<your
provider’s name>
- provider’s name – the name of your ContentProvider
class
- Two types of URIs: directory- and id-based URIs. If no id is
specified a URI is automatically a directory-based URI.
- You use directory-based URIs to access multiple elements of
the same type (e.g. all songs of a band). All CRUD-operations are possible with directory-based URIs.
- You use id-based URIs if you want to access a specific
- element. You cannot create objects using an id-based URI –
but reading, updating and deleting is possible.
- The path of content URIs can contain additional information
to limit the scope. The MediaStore content provider for example distinguishes between audio and other types.
CRUD in ProviderResolver
Method Usage delete Deletes the object(s) for the URI
- provided. The URI can be item- or
directory-based insert Inserts one object. The URI must be directory-based query Queries for all objects that fit the URI. The URI can be item- or directory- based update Updates one or all object(s). The URI can be item- or directory-based
The arguments of the query method
Type Name Usage URI uri The URI of the object(s) to
- access. This is the only
argument that must not be null String[] projection This String array indicates which columns/attributes of the
- bjects you want to access
String selection With this argument you can determine which records to return String[] selectionArgs The binding parameters to the previous selection argument String sortOrder If the result should be ordered you must use this argument to determine the sort order
Cursor object: return value of the query method
- The cursor is used to navigate between the rows
- f the result and to read the columns of the current
- row. Cursors are important resources that have to be
closed whenever you have no more use for them –
- therwise you keep valuable resources from being
released.
Querying for data
- UserDictionary is probably the easiest standard provider available and
thus well suited for showing the concepts. But by default this provider has no entries, so you better add some words first.
Cursor example
ContentResolver resolver = getContentResolver(); String[] projection = new String[]{BaseColumns._ID, UserDictionary.Words.WORD}; Cursor cursor = resolver.query(UserDictionary.Words.CONTENT_URI, projection, null, null, null); if (cursor.moveToFirst()) { do { long id = cursor.getLong(0); String word = cursor.getString(1); // do something meaningful } while (cursor.moveToNext()); }
Inserting new records
- Very often your app needs to insert data to Android built-in content
providers because you want to add events to the Calendar provider, people to the Contacts provider, words to the UserDictionary provider and so on.
- The correct content URI for inserts can only be a directory-based
URI because only these represent a collection of related items.
- The values to insert are specified using a ContentValues object.
- This object is just a collection of key/value pairs. The keys of your
ContentValues object must match columns/attributes of the
- bjects you want to update – otherwise you will get an exception.
For all columns of the new object for which no key/value-pair is provided the default value is used – which most often is null.
The arguments of the insert method
Type Name Usage URI uri The directory-based URI to which to add the
- bject. This argument
must not be null ContentValues values The values for the object to add. This argument also must not be null ContentValues values = new ContentValues(); values.put(Words.WORD, "Beeblebrox"); resolver.insert(UserDictionary.Words.CONTENT_URI, values);
Updating data
- The arguments of the update method: ContentValues object and
- ptionally also a where-clause and arguments for this where-clause.
- The arguments of the update method
Type Name Usage URI uri The URI of the object(s) to access. This argument must not be null ContentValues values The values to substitute the current data with. This argument also must not be null String selection With this argument you can determine which records to update String[] selectionArgs The binding parameters to the previous selection argument
Update example
values.clear(); values.put(Words.WORD, "Zaphod"); Uri uri = ContentUris.withAppendedId(Words.CONTENT_URI, id); long noUpdated = resolver.update(uri, values, null, null);
Note
- The keys of your ContentValues object match
columns/attributes of the objects you want to update – otherwise you would get an exception. The update method changes only those columns for which keys are present in the ContentValues
- bject.
- ContentUris.withAppendedId() helper method create
an id-based URI from a directory-based one. You use it all the time since content providers only provide constants for directory-based
- URIs. So whenever you want to access a specific object you should
use this method.
- If change only one record, a URI with an appended ID is sufficient.
But if you want to update multiple values, you should use the normal URI and a selection clause.
- Call values.clear() will resets and recycle the
ContentValues object
Deleting data
It finally deletes the word with the selection and selectionArgs
- arguments. The array of the selectionArgs argument is used to
substitute all question marks found in the selection argument.
long noDeleted = resolver.delete (Words.CONTENT_URI, Words.WORD + " = ? ", new String[]{"Zaphod"});
The arguments of the delete method
ype Name Usage URI uri The URI of the object(s) to access. This is the
- nly argument which
must not be null String selection With this argument you can determine which records to delete String[] selectionArgs The binding parameters to the previous selection argument
Finding the data
- One app has a database and a registered content provider. And Another
app uses a content resolver to request data from a content provider.
- The Android system uses the URI to find the correct provider to send the
request to and The content provider uses the URI to find the data and returns it to the content resolver.
- Match a Uri by The Uri Matcher You need to have an address for any
data that you want to access in a database by CONTENT_URI
- Then when making a query you’d pass the CONTENT_URI as the URI for
the data that you are querying.
Using the Content Provider
- 1. Creating the Content Provider’s database
The onCreate() method of your content provider is called to setup CP when your app starts
Interacting with the database
- If you’re using a SQLite database then you can use any of
the SQLiteDatabase class’s query and transaction methods.
- These are the methods you’ll need to include in your
content provider:
- getType() – returns the content providers MIME type
- query() – returns a Cursor containing the set of required
data
- insert() – adds data to the database
- delete() – deletes data in the database
- update() – updates data in the database
The query
- The query will return a Cursor object.
- These are the general steps to follow:
- Open the database
- Create a SQLiteQueryBuilder object
- Use a switch statement to match the URI
- Build your query
- Execute the query
- Return the cursor
Inserting data
- These are the general steps to follow:
- Open the database
- Put your data into a ContentValues object
- Execute the insert
- Construct the URI of the inserted row
- Notify observers of modified database
- Return the URI of the inserted row
Deleting data
- These are the general steps to follow:
- Open the database
- Use a switch statement to create your
selection and selection argument options
- Execute the delete
- Notify observers of modified database
- Return the number of deleted rows
Updating data
- These are the general steps to follow:
- Open the database
- Put your data into a ContentValues object
- Use a switch statement to create your selection
and selection argument options
- Execute the update
- Notify observers of modified database
- Return the number of rows updated
Content Resolver
- You need to use a Content Resolver to access the database from
another app
- Apps wanting to access the database would use their content
resolver’s methods.
- The content resolver would then pass the request to the other
app's content provider. The provider would then return the result.
- You can still use the SQLiteDatabase methods to access the
database
- You can still use the SQLiteDatabase methods without using a
content resolver to query and modify the database if you wish. But you can only do this from within the app that created the
- database. See the Using a SQLite database in Android tutorial.