Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Storage: Part 4 (Content Providers). Content Providers Content providers allow the sharing of data between applications. Inter-process communication.

Similar presentations


Presentation on theme: "Data Storage: Part 4 (Content Providers). Content Providers Content providers allow the sharing of data between applications. Inter-process communication."— Presentation transcript:

1 Data Storage: Part 4 (Content Providers)

2 Content Providers Content providers allow the sharing of data between applications. Inter-process communication (IPC) and content providers are the only ways to share application data. Content providers are one of the primary building blocks of Android applications (along with activities, services, and broadcast receivers). A content provider is implemented as a subclass of class ContentProvider (in package android.content ). Android ships with a number of content providers for common data types (audio, video, images, contacts, etc.) –See documentation for package android.provider. –Most of these providers require permission to read their data. Slide 2©SoftMoore Consulting

3 Selected Android Content Providers Browser – bookmarks, browser history, etc. Contacts – names, phone numbers, etc. Media Store – audio, video, images, etc. Calendar – user’s calendar events Settings – Bluetooth settings, ringtones, Wi-Fi settings, locale, etc. User Dictionary – user-defined words for use with predictive text input. Slide 3©SoftMoore Consulting

4 Overview of Content Providers Applications can extend the abstract class ContentProvider (in package android.content ) and override the appropriate methods to allow shared access to their data. Regardless of how a content provider actually stores its data, it exposes that data as though it were a simple database table. Note: Every record must include a numeric _id field that uniquely identifies the record within the table. Content providers encapsulate data and make it available to other applications though the ContentResolver interface. Slide 4©SoftMoore Consulting

5 Overview of Content Providers (continued) Accessing the data exposed by a content provider is very similar to accessing the data in a SQLite database via the convenience methods except that the content provider methods have a URI as their first parameter rather than a database. Content providers are useful for building applications with databases even if the data is not shared outside of the application. A content provider must be declared in the application manifest ( AndroidManifest.xml ) using a element, similar to the way that each activity must be declared. Slide 5©SoftMoore Consulting

6 Example: Querying a SQLite Database Versus Querying a Content Provider Querying a SQLite database using convenience methods SQLiteOpenHelper openHelper =... ; SQLiteDatabase db = openHelper.getReadableDatabase(); String tableName =... ; String[] columns =... ; String orderBy =... ; Cursor cursor = db.query(tableName, columns, null, null, null, null, orderBy); Querying a content provider ContentResolver cr = getContentResolver(); Uri uri =... ; String[] columns =... ; String orderBy =... ; Cursor cursor = cr.query(uri, columns, null, null, null, null, orderBy); Slide 6©SoftMoore Consulting

7 Example: Inserting into a SQLite Database Versus Inserting into a Content Provider Inserting into a SQLite database using convenience methods SQLiteOpenHelper openHelper =... ; SQLiteDatabase db = openHelper.getWritableDatabase(); String tableName = "... "; ContentValues values = new ContentValues(); values.put("... ", "... ");... // additional values.put() statements db.insert(tableName, null, values); Inserting into a content provider ContentResolver cr = getContentResolver(); Uri uri =... ; ContentValues values = new ContentValues(); values.put("... ", "... ");... // additional values.put() statements cr.insert(uri, null, values); Slide 7©SoftMoore Consulting

8 URIs Each content provider exposes a public URI (Uniform Resource Identifier) that uniquely identifies its data set. A content provider that controls multiple data sets (multiple tables) exposes a separate URI for each one, and possibly joins of the tables. Classes Uri and Uri.Builder (in package android.net ) provide support for creating and accessing URIs for content providers. Slide 8©SoftMoore Consulting

9 URI Format The URI for a content provider is a string of the form content://authority/path/id content:// – the standard required prefix that identifies the data as being controlled by a content provider. authority – a string that uniquely identifies the content provider; e.g., the provider package name with table name. path – zero or more segments, separated by a forward slash (/), that identify some subset of the provider’s data. Most providers use the path part to identify individual tables. id – the identifier of the specific record being requested. If the request is not limited to a single record, this segment and the trailing slash are omitted. Slide 9©SoftMoore Consulting

10 URI Constants A content provider usually defines constants in a “contract” class for its URIs to simplify client code and make future updates cleaner. public static final Uri CONTENT_URI =...; The URI constant is used in all interactions with the content provider. Android defines constants for all the providers that come with the platform. –Media Store classes (e.g., MediaStore.Audio.Albums ) define two constants their data, INTERNAL_CONTENT_URI and EXTERNAL_CONTENT_URI –Class Browser defines two constants for its data, BOOKMARKS_URI and SEARCHES_URI. Slide 10©SoftMoore Consulting

11 Content URI Examples content://user_dictionary/words –UserDictionary.Words.CONTENT_URI content://user_dictionary/words/4 –row from user dictionary with _id = 4 –can be constructed as ContentUris.withAppendedId(UserDictionary.Words.CONTENT_URI,4); content://edu.citadel.android.emergency/emergency_contacts –EmergencyContract.CONTENT_URI (sample application) Slide 11©SoftMoore Consulting Applications usually just use content URI constants declared in in a contract class.

12 Class ContentResolver Content providers encapsulate data and make it available to other applications though the ContentResolver interface. When a request is made via a ContentResolver the system inspects the authority of the given URI and passes the request to the content provider registered with the authority. The content provider can interpret the rest of the URI however it wants. Most ContentResolver methods take the URI as their first parameter. The URI identifies which provider the ContentResolver should talk to and which table of the provider is being targeted. Slide 12©SoftMoore Consulting

13 Class ContentProvider Class ContentProvider is an abstract class in package android.content. Class ContentProvider contains several abstract methods that resemble the convenience methods use to access a SQLite database. To create a content provider, extend this abstract class and provide implementations for the abstract methods (shown on next slide). Slide 13©SoftMoore Consulting

14 Abstract Methods in Class ContentProvider onCreate() –used to initialize the provider query(Uri, String[], String, String[], String) –returns data to the caller insert(Uri, ContentValues) –inserts new data into the content provider update(Uri, ContentValues, String, String[]) –updates existing data in the content provider delete(Uri, String, String[]) –deletes data from the content provider getType(Uri) –returns the MIME type of data in the content provider Slide 14©SoftMoore Consulting

15 Content Provider Permissions A content provider application can specify permissions (as part of the element in the application manifest) that other applications must have in order to access the provider’s data. Other applications request the permissions they need in order to access the provider. End users see the requested permissions when they install the application. If a content providers application doesn’t specify any permissions, then other applications have no access to the provider's data. However, components within the application always have full read and write access, regardless of the specified permissions. Slide 15©SoftMoore Consulting

16 Querying a Content Provider Querying a content provider requires three pieces of information: –The URI that identifies the provider –The names of the data fields you want to receive –The data types for those fields It is also possible to query a particular record if you know the ID for that record. Two methods can be used to query a content provider: –ContentResolver.query() –Activity.managedQuery() Slide 16©SoftMoore Consulting Activity.managedQuery() was deprecated in API 11 with the recommendation to use ContentResolver.query() along with CursorLoader and LoaderManager.

17 Example: Querying Contacts for the Display Name Uri uri = ContactsContract.Contacts.CONTENT_URI; String[] columns = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME }; String orderBy = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"; ContentResolver cr = getContentResolver(); Cursor cursor = cr.query(uri, columns, null, null, orderBy); Slide 17©SoftMoore Consulting

18 Creating a Content Provider To create a content provider you must: Set up a system for storing the data (e.g., a SQLite database). Extend the ContentProvider class to provide access. –Override the abstract methods onCreate(), insert(), query(), etc. –Note: Some methods can have trivial implementations. For example, if other applications are only allowed to read content, only methods onCreate() and query() need nontrivial implementations. Declare the content provider in the application’s manifest file ( AndroidManifest.xml ). Slide 18©SoftMoore Consulting

19 Creating a Content Provider (continued) To create a content provider you should: Define a public static final Uri named CONTENT_URI that represents the full “ content: ” URI managed by the content provider. To guarantee that the string has a unique value, use the fully-qualified class name of the content provider converted to lowercase. Define the column names that the content provider will return to clients; e.g., the column names of the underlying database. Also define public static String constants that clients can use to specify the columns in queries and other instructions. Be sure to include an integer column named _id. Slide 19©SoftMoore Consulting

20 Creating a Content Provider (continued) Carefully document the data type of each column. If you are handling a new data type, define a new MIME type to return in your implementation of ContentProvider.getType(). –There is one form of the MIME type for a single record and another for multiple records. (See the link for “Content Providers” at the end of this section). –Use the Uri methods to help determine what is being requested. Slide 20©SoftMoore Consulting

21 Example: Content Provider for Emergency Contacts in Previous Section public class EmergencyProvider extends ContentProvider { private static final String AUTHORITY = EmergencyContract.AUTHORITY; private static final String TABLE_NAME = EmergencyContract.TABLE_NAME; private static final Uri CONTENT_URI = EmergencyContract.CONTENT_URI; public static final int CONTACTS = 1; // for contacts table public static final int CONTACTS_ID = 2; // for single contact private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);... } Slide 21©SoftMoore Consulting See handout EmergencyProvider.java. Pay special attention to use of UriMatcher.

22 Relevant Links Content Providers http://developer.android.com/guide/topics/providers/content-providers.html Android Content Providers http://www.tutorialspoint.com/android/android_content_providers.htm An Android Content Provider Tutorial http://www.techotopia.com/index.php/An_Android_Content_Provider_Tutorial Loading Contacts with Content Providers https://github.com/codepath/android_guides/wiki/Loading-Contacts-with-Content-Providers Slide 22©SoftMoore Consulting


Download ppt "Data Storage: Part 4 (Content Providers). Content Providers Content providers allow the sharing of data between applications. Inter-process communication."

Similar presentations


Ads by Google