Friday, August 29, 2014

Content Provider

Database is accessible to only the package that created it.

Android's way of sharing data across packages is through the use of content providers.

A content provider behaves very much like a database - you can query it, edit its contents, as well as add or delete content.

The data can be stored in a database, in files, or even over a network.

Android ships with many useful content providers

Browser : Stores data such as browser bookmarks, browser history, and so on
CallLog : Stores data such as missed calls, call details, and so on
Contacts : Stores contact details
MediaStore : Stores media fi les such as audio, video, and images
Settings : Stores the device’s settings and preferences

Querying a content provider

To query a content provider, you specify the query string in the form of a URI, with an optional
specifier for a particular row.

<standard_prefix>://<authority>/<data_path>/<id>

standard_prefix
The standard prefix for content providers is always content://

authority
The authority specifies the name of the content provider
Eg:
     contacts: Built-in contacts provider
     <fully qualified name>: for third party content providers

data_path
The data path specifies the kind of data requested
Eg.
    people: content://contacts/people

id
The id specifies the specific record requested
Eg.
content://contacts/people/2

Example Query Strings:

content://media/internal/images
content://media/external/images
content://call_log/calls
content://browser/bookmarks

Predefined Query String Constants

you can use a list of predefi ned query string constants in Android to specify the URI for the different data types.

Uri allContacts = Uri.parse(“content://contacts/people”);

Uri allContacts = ContactsContract.Contacts.CONTENT_URI;

Some examples of predefi ned query string constants

Browser.BOOKMARKS_URI
Browser.SEARCHES_URI
CallLog.CONTENT_URI
MediaStore.Images.Media.INTERNAL_CONTENT_URI
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
Settings.CONTENT_URI

To access the phone number of a contact, you need to query against the URI stored in ContactsContract.CommonDataKinds.Phone.CONTENT_URI

https://github.com/coderetriever/Android/tree/master/Provider

Projections

Specify the exact columns to return by creating an array containing the names of the column to return

Cursor c = managedQuery(allContacts, projection, null, null, null);

CursorLoader cursorLoader = new CursorLoader(this, allContacts, projection, null, null, null);
Cursor c = cursorLoader.loadInBackground();

String[] projection = new String[]
{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER};

Filtering 

SQL WHERE clause to filter the result of the query

third and fourth parameters
c = managedQuery(allContacts, projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ‘%Lee’”, null, null);

Cursor c;
if (android.os.Build.VERSION.SDK_INT <11) {
//---before Honeycomb---
c = managedQuery(allContacts, projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ?”,
new String[] {“%Lee”}, null);

fourth and fifth parameters
CursorLoader cursorLoader = new CursorLoader(
this,
allContacts,
projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ‘%Lee’”,
null ,
null);
c = cursorLoader.loadInBackground();

CursorLoader cursorLoader = new CursorLoader(
this,
allContacts,
projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ?”,
new String[] {“%Lee”},
null);
c = cursorLoader.loadInBackground();

Sorting

SQL ORDER BY clause to sort the result of the query

last parameter of managedQuery
c = managedQuery(allContacts, projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ?”,
new String[] {“%Lee”},
ContactsContract.Contacts.DISPLAY_NAME + “ ASC”);

Creating a custom content provider

To create a new Content Provider, extend the abstract ContentProvider class.

Override the onCreate method to create (and initialize) the underlying data source you’re planning to publish with this provider

import android.content.*;
import android.database.Cursor;
import android.net.Uri;
import android.database.SQLException;

public class MyProvider extends ContentProvider {

  @Override
  public boolean onCreate() {
    // TODO Construct the underlying database.
    return true;
  }
}

Expose a public static CONTENT_URI property that returns the full URI of this provider

content://com.<CompanyName>.provider.<ApplicationName>/<DataPath>

Content URIs can represent either of two forms:

Request for all values of that type (in this case all elements)
content://com.paad.provider.myapp/elements

Request for a single record
content://com.paad.provider.myapp/elements/5

It’s good practice to support access to your provider for both of these forms. The simplest way to do this is to use a UriMatcher

Using the UriMatcher to handle single or multiple query requests

public class MyProvider extends ContentProvider {

  private static final String myURI = "content://com.paad.provider.myapp/items";
  public static final Uri CONTENT_URI = Uri.parse(myURI);

  @Override
  public boolean onCreate() {
    // TODO: Construct the underlying database.
    return true;
  }

  // Create the constants used to differentiate between the different URI 
  // requests.
  private static final int ALLROWS = 1;
  private static final int SINGLE_ROW = 2;
  
  private static final UriMatcher uriMatcher;

  // Populate the UriMatcher object, where a URI ending in 'items' will correspond to a request for all items, and 'items/[rowID]' represents a single row.
  static {
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    uriMatcher.addURI("com.paad.provider.myApp", "items", ALLROWS);
    uriMatcher.addURI("com.paad.provider.myApp", "items/#", SINGLE_ROW);
  }
}

You can use the same technique to expose alternative URIs for different subsets of data

Exposing Access to the Data Source

Expose queries and transactions on your Content Provider by implementing the delete, insert, update, and query methods
These methods are the interface used by the Content Resolver to access the underlying data

Defining the MIME type that identifies the data the provider returns.
Override the getType method to return a String that uniquely describes your data type
Single item vnd.<companyname>.cursor.item/<contenttype>
All items vnd.<companyName>.cursor.dir/<contenttype>

@Override
public Cursor query(Uri uri, 
                    String[] projection, 
                    String selection, 
                    String[] selectionArgs, 
                    String sort) {
      
  // If this is a row query, limit the result set to the passed in row.        
  switch (uriMatcher.match(uri)) {
    case SINGLE_ROW : 
      // TODO: Modify selection based on row id, where:
      // rowNumber = uri.getPathSegments().get(1));
  }
  return null;
}

@Override
public Uri insert(Uri _uri, ContentValues _initialValues) {
  long rowID = [ ... Add a new item ... ]
        
  // Return a URI to the newly added item.
  if (rowID > 0) {
    return ContentUris.withAppendedId(CONTENT_URI, rowID);
  }
  throw new SQLException("Failed to add new item into " + _uri);
}

@Override
public int delete(Uri uri, String where, String[] whereArgs) {
  switch (uriMatcher.match(uri)) {
    case ALLROWS: 
    case SINGLE_ROW:
    default: throw new IllegalArgumentException("Unsupported URI:" + uri);
  }
}

@Override
public int update(Uri uri, ContentValues values, String where, String[] 
whereArgs) {
  switch (uriMatcher.match(uri)) {
    case ALLROWS: 
    case SINGLE_ROW:
    default: throw new IllegalArgumentException("Unsupported URI:" + uri);
  }
}

@Override
public String getType(Uri _uri) {
  switch (uriMatcher.match(_uri)) {
    case ALLROWS: return "vnd.paad.cursor.dir/myprovidercontent";
    case SINGLE_ROW: return "vnd.paad.cursor.item/myprovidercontent";
    default: throw new IllegalArgumentException("Unsupported URI: " + _uri);
  }
}

Registering Your Provider

Once you have completed your Content Provider, it must be added to the application manifest.

Use the authorities tag to specify its base URI,

<provider android:name="MyProvider" android:authorities="com.paad.provider.myapp"/>

USING CONTENT PROVIDERS

Each application Context includes a ContentResolver instance

ContentResolver cr = getContentResolver();

Querying for Content

Using the query method on the ContentResolver object, pass in:

The URI of the Content Provider data you want to query
A projection that lists the columns you want to include in the result set\
A where clause that defines the rows to be returned. an include ? wildcards that will be
replaced by the values passed into the selection argument parameter
An array of selection argument strings that will replace the ?s in the where clause
A string that describes the order of the returned rows

ContentResolver cr = getContentResolver();

// Return all rows
Cursor allRows = cr.query(MyProvider.CONTENT_URI, null, null, null, null);

// Return all columns for rows where column 3 equals a set value
// and the rows are ordered by column 5.
String where = KEY_COL3 + "=" + requiredValue;
String order = KEY_COL5;
Cursor someRows = cr.query(MyProvider.CONTENT_URI, 
                           null, where, null, order);

Adding, Updating, and Deleting Content

To perform transactions on Content Providers, use the delete, update, and insert methods on the ContentResolver object.

Inserts

// Get the Content Resolver
ContentResolver cr = getContentResolver();

// Create a new row of values to insert.
ContentValues newValues = new ContentValues();

// Assign values for each row.
newValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]

Uri myRowUri = cr.insert(MyProvider.CONTENT_URI, newValues);

// Create a new row of values to insert.
ContentValues[] valueArray = new ContentValues[5];

// TODO: Create an array of new rows
int count = cr.bulkInsert(MyProvider.CONTENT_URI, valueArray);

Deletes

ContentResolver cr = getContentResolver();

// Remove a specific row.
cr.delete(myRowUri, null, null);
// Remove the first five rows.
String where = "_id < 5";
cr.delete(MyProvider.CONTENT_URI, where, null);

Updates

// Create a new row of values to insert.
ContentValues newValues = new ContentValues();

// Create a replacement map, specifying which columns you want to
// update, and what values to assign to each of them.
newValues.put(COLUMN_NAME, newValue);

// Apply to the first 5 rows.
String where = "_id < 5";

getContentResolver().update(MyProvider.CONTENT_URI, newValues, where, null);

Accessing Files in Content Providers

Content Providers represent files as fully qualified URIs rather than as raw file blobs

// Insert a new row into your provider, returning its unique URI.
Uri uri = getContentResolver().insert(MyProvider.CONTENT_URI, newValues);

try {
  // Open an output stream using the new row's URI.
  OutputStream outStream = getContentResolver().openOutputStream(uri);
  // Compress your bitmap and save it into your provider.
  sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
}
catch (FileNotFoundException e) { }


No comments:

Post a Comment