Content Provider in Android

Android content provider- this article explains- how to retrieve or access data from the content provider, modifying and deleting data from the existing content provider. Defining a new content provider is beyond the scope of this document. To learn about creating a new content provider, please visit https://android-app-market.com/content-providers.html.

Android

Android is a mobile operating system developed by Google. Android package contains mobile operating system, middleware and some key applications. Android sdk comes with the tools and API which helps in writing application for Android devices. Java is used as programming language to create Android applications. Google provides three SDKs to develop applications depending upon development environment for example Windows, Linux and Mac. Android application could be develop using different IDE but Google provide full support for the development on Eclipse IDE.

This article will explain about Android content provider which is one feature of the Android platform. Content provider is used to store and access the data across applications on Android platform.

Content Provider in Android

In Android, application data is stored privately for each application. Content provider is the only way to share data in between different applications. Data stored by any other mean like file system, database etc. is private to the application which has stored it and can't be accessed by other applications.

Android comes with a number of content providers for example personal contact information, audio, images, call logs etc. List of all available content providers is present in android.provider package. Developers can query these providers for the data they contain. They have to provide proper permissions to read data from content providers.

If you want to make your data public, then android provides you two ways to do it

  • Create one inherited class from the ContentProvider base class.
  • Add data to an existing provider – if there is one that controls the same type of data and we have write permission on it.

Reading/Accessing data from Content provider in Android

Data can be accessed from the content provider by two methods ContentResolver.query() and Activity.managedQuery().

Argument list and return type for both methods is same but, in case of manageQuery, activity can manage the life cycle of the returned cursor object. On the other hand, ContentResolver.query() returns an unmanaged Cursor object.

In case of managed Cursor, Cursor gets unloaded at the time of pause and send re-query at the time of restart. We can begin managing an unmanaged Cursor object by calling startManagingCursor method of Activity class.

manageQuery Example

public final Cursor managedQuery (Uri uri, String[] projection, String selection, String[]   selectionArgs, String sortOrder)

Parameters
uri --The URI of the content provider to query.
projection --List of columns to return.
selection --SQL WHERE clause.
selectionArgs --The arguments to selection, if any ?s are present
sortOrder --SQL ORDER BY clause.

Returns
The Cursor returned by query ().

First argument of the managedQuery is the uri of the content provider, which identifies a particular ContentProvider and dataset.

To fetch one specific record, append the _Id value for that record to the URI. There are two functions to append ID ContentUris.withAppendedID() and Uri.withAppendedPath().

Following code snippet demonstrates the querying data from the content provider for a specific record

import android.provider.CallLog;
import android.content.ContentUris;
import android.net.Uri;
import android.database.Cursor;

//Use the ContentUris method to produce the base URI for the contact with _ID = 1.
Uri myPerson = ContentUris.withAppendedId(Calls.CONTENT_URI, 1);

// Alternatively, Uri method can also be used to produce the base URI.
// It takes a string rather than an integer.
Uri myPerson = Uri.withAppendedPath(Calls.CONTENT_URI, "1");

// query for this specific record:
Cursor cur = managedQuery (myPerson, null, null, null, null);

Another example is to retrieve call logs in descending order:

import android.provider.CallLog;
import android.database.Cursor;

// Form an array specifying the columns to return.
String[] callLogColumnList = new String[] {
               CallLog.Calls.NUMBER,
             CallLog.Calls.CACHED_NAME,
             CallLog.Calls.DATE,
             CallLog.Calls.DURATION,
             CallLog.Calls.TYPE
                          };

// Get the base URI for the People table in the Contacts content provider.
Uri callLogs = CallLog.Calls.CONTENT_URI;

// Make the query.
Cursor managedCursor = managedQuery (callLogs,
                 callLogColumnList, // which columns to return
                 null,       // Which rows to return (all rows)
                 null,       // Selection arguments (none)
                 CallLog.Calls.DATE + "DESC" //results in descending order by date
);

In the above example, query retrieves data from the call Log table of the CallLog content provider. It gets the name, phone number, date, duration and call type for each call log entry.

Query returns a cursor which contains the record set of the result set. In case of querying for a specific record by ID, cursor will contain only one value. Otherwise it will contain multiple values or will be empty depending upon the number of the records saved.

We can read data from the specific field in the record but we must know the data type of the field because cursor object has different functions for reading data of different types. For example, getString(), getInt() and getFloat() are used to get data of corresponding data types. However, for most types, Cursor provides string representation of the data.

Following code snippet demonstrates retrieving data from the cursor:

Modifying data in Content provider of Android

import android.provider.CallLog;

private void getColumnData(Cursor cur){
    if (cur.moveToFirst()) {

        String name;
        String phoneNumber;
        int nameColumn = cur.getColumnIndex(CallLog.Calls.CACHED_NAME);
        int phoneColumn = cur.getColumnIndex(CallLog.Calls.NUMBER);
        String imagePath; 

        do {
            // Get the field values
            name = cur.getString(nameColumn);
            phoneNumber = cur.getString(phoneColumn);

     // Do something with the values.
            ...
        } while (cur.moveToNext());
    }
}

a. Adding new records to Content provider

To add new records to Content provider, follow these steps:

  • Create an object of ContentValues.
  • Store key value pair corresponding to each column name and value in the Content Values object.
  • Call ContentResolver.insert() and pass the URI and ContentValues object to it.

ContentResolver.insert() will return the URI of the newly added row. It can be further understood by the following code snippet:

import android.provider.Contacts.People;
import android.content.ContentResolver;
import android.content.ContentValues;

ContentValues values = new ContentValues();

// Add Abraham Lincoln to contacts and make him a favorite.
values.put(People.NAME, "Abraham Lincoln");
// 1 = the new contact is added to favorites
// 0 = the new contact is not added to favorites
values.put(People.STARRED, 1);

Uri uri = getContentResolver().insert(People.CONTENT_URI, values);

 b. Adding new values to the existing record in Content provider

To add new values to the existing record in to Content provider, create an object of the ContentValues and add key value pair corresponding to new values, then call insert method of the ContentResolver class and pass the URI of that specific record and ContentValues object.

c. Batch Update of Records in Content provider

To batch update a group of records in to Content provider, call ContentResolver.update() method with the columns and values to change.

d. Deleting a Record from Content provider

To delete a specific record from Content provider, call ContentResolver.delete() method with the URI for that specific record. To delete more than one record, call ContentResolver.delete() method with the URI, as the first argument and an SQL WHERE clause defining which rows to delete, as second argument.

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>