Android Content Providers & SQLite COMP467 Mobile Module
Why Content Providers The underlying Linux kernel treats each Android App as a separate user/process. Apps are “sandboxed” such that by default direct data sharing is not allowed. Content Providers are a way to share data across apps. Content Providers centralize data into one place and have other apps access it. Together, providers and provider clients offer a consistent, standard interface to data that also handles inter-process communication and secure data access.
Content Providers Intro Functions much like a database providing query(), insert(), delete() and update() methods. In most cases, data is stored in a SQlite databases or flat files
Example Content Providers Contacts MediaStore Bookmarks User dictionary Settings
Content Provider APIs Client Content Provider Provider Application Data
Content Provider Intro You must extend the ContentProvider class to create your content provider. E.g. public class KbContentProvider extends ContentProvider { // }
Content URI Used to specify a particular content provider Four Parts: Scheme: For providers is always content:// Authority: Has to be unique for each content provider. The convention is to use Java Package rules (reversed domain name of org + qualifier for each provider. content://authority/optionalPath/optionalId
Content URI Path:This indicates the type of data that this particular provider provides. For example, if you are getting all the contacts from the Contacts content provider, then the data path would be people and URI would look like this content://contacts/people ID: This specifies the specific record requested. For example, if you are looking for contact number 5 in the Contacts content provider then URI would look like thiscontent://contacts/people/5.
Content Provider Methods onCreate() This method is called when the provider is started. query() This method receives a request from a client. The result is returned as a Cursor object. insert()This method inserts a new record into the content provider.
Content Provider Methods Cont. delete() This method deletes an existing record from the content provider. update() This method updates an existing record from the content provider. getType() This method returns the MIME type of the data at the given URI.
Content Types First defined in RFC 1049 and refined in RFC 2045. Consists of a type and a subtype. Eg. image/png
Using Existing Content Providers Use Content Resolver to interact with Content Provider. Content Resolver uses authority part of URI to determine which provider to use. Obtain the ContentResolver object by calling the getContentResolver() method on the Context object.
Content Resolver A client application accesses the data from a content provider with a ContentResolver object. The ContentResolver object provides query(), insert(), update(), and delete() methods for accessing data from a content provider. The ContentResolver object invokes identically-named methods on an instance of a concrete subclass of ContentProvider, which typically resides in a separate application process. The ContentProvider acts as an abstraction layer between its data store and the external presentation of data. The ContentResolver object and the ContentProvider object automatically handle the details of inter-process communication. https://newcircle.com/s/post/1375/android_content_provider_tutorial
Content Resolver Methods Gives access to Content Provider so it must implement CRUD. 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
Example Content Resolver Query operation on UserDictionary Here are the parameters to the method Returns a Cursor object that can be used to traverse the returned records. 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 objects you want to access String selection With this argument you can determine which records to return selectionArgs The binding parameters to the previous selection argument sortOrder If the result should be ordered you must use this argument to determine the sort order
Query Code Snippett 1 ContentResolver resolver = getContentResolver(); 2 String[] projection = new String[]{BaseColumns._ID, UserDictionary.Words.WORD}; 3 Cursor cursor = 4 resolver.query(UserDictionary.Words.CONTENT_URI, 5 projection, 6 null, 7 null, 8 null); 9 if (cursor.moveToFirst()) { 10 do { 11 long id = cursor.getLong(0); 12 String word = cursor.getString(1); 13 // do something meaningful 14 } while (cursor.moveToNext()); 15}
Insert Snippet Type Name Usage URI uri The directory-based URI to which to add the object. This argument must not be null ContentValues values The values for the object to add. This argument also must not be null 1 ContentValues values = new ContentValues(); 2 values.put(Words.WORD, "Beeblebrox"); 3 resolver.insert(UserDictionary.Words.CONTENT_URI, values);
Delete Code Snippet 1 long noDeleted = resolver.delete Type Name Usage URI uri The URI of the object(s) to access. This is the only 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 1 long noDeleted = resolver.delete 2 (Words.CONTENT_URI, 3 Words.WORD + " = ? ", 4 new String[]{"Zaphod"});
Update 1 values.clear(); 2 values.put(Words.WORD, "Zaphod"); 3 Uri uri = ContentUris.withAppendedId(Words.CONTENT_URI, id); 4 long noUpdated = resolver.update(uri, values, null, null); 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
Contract classes are not included automatically with a provider A contract class defines constants that help applications work with the content URIs, column names, and other features of a content provider. Contract classes are not included automatically with a provider The provider’s developer has to define them and then make them available to other developers.
Contract Classes Cont. Many of the providers included with the Android platform have corresponding contract classes in the package android.provider. For example, the User Dictionary Provider has a contract class UserDictionary containing content URI and column name constants. The content URI for the "words" table is defined in the constant UserDictionary.Words.CONTENT_URI. The UserDictionary.Words class also contains column name constants.
SQliteOpenHelper Used to create and update a Sqlite database within an Android App. onCreate() – called when the database is accessed and has not been created. onUpdate() – Called when the version number has increased in your app code. Both methods are passed a SQLiteDatabase object as a parameter.
Sqlite Example Let’s look at this tutorial that creates and uses a Sqlite database within an app. This does not require the content provider framework http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ http://www.techotopia.com/index.php/An_Android_SQLite_Database_Tutorial
References https://thenewcircle.com/s/post/1375/android_content_provider_tutorial http://www.tutorialspoint.com/android/android_content_providers.htm http://www.vogella.com/tutorials/AndroidSQLite/article.html http://developer.android.com/guide/topics/providers/content-provider-creating.html http://www.grokkingandroid.com/android-tutorial-content-provider-basics/