Android Tutorials for Beginners Part-4: Content Provider

Recommended by 32 users

Dec 19, 2012
Android Tutorials for Beginners Part-4: Content Provider
Add to Bookmark Email this Post 8.3K    28

 

In our previous Android tutorials for beginners, we discussed the first three building blocks of Android: ActivityIntent and Services. This article is fourth in this series of Android Tutorials for beginners and discusses Content Provider, which is another very important component of the Android System.

Content Provider is your Android system’s middleman, facilitating data interchange between different Android applications. Let us get a little into the details of that in this Android tutorial.

Android Tutorial for beginners-4 Bonus: Download Content Provider Code here. You would want this code once you have gone through the tutorial! :) 

Android Tutorials: Content Provider

Content Provider facilitates access to a central data store or warehouse to allow data sharing and data manipulation across different applications.

Here are a few examples of default Content Providers in Android system’s API:

Android Tutorials: Default Content Providers in Android system

These content providers allow the user abstraction from an underlying database. Generally, Content Providers use SQLite to store underlying database.

Let us take the ever-helpful example of the good old Facebook application, that has helped us simplify things in previous Android Tutorials as well!

All of you have at some point in your social networking life, uploaded a pic to your Facebook timeline, right! How do you do it?

On clicking the Photo Button on the wall, you get to the photo gallery. From there you can choose a photo to upload.

Having read the previous articles of Android Tutorials series, you know about Activities and Intents; therefore, you know that this is what happens:

Your Facebook Wall is an “ACTIVITY”. As you click on the Photo Button, an “INTENT” is passed, that conveys the message and the “CONTENT PROVIDER” (Photo Gallery) opens. The photo is uploaded using a network upload “SERVICE”.

Android tutorials for beginners: Content Provider example

Watch this live video to know how Content Provider works inside your Facebook Application. 

Why does Android System need Content Providers?

The need for Content Providers arises because the database created in one application is not visible to a second application.

It is simple to create and store database in different applications using SQLite, however the problem is this, a database in Android is private to the application that creates it. There is no common storage area in Android that every application can access. Therefore, for different applications to use a database, Android system needs an interface that allows such inter-application and inter-process data exchange. This is where content provider comes to play.

Do I really need a Content Provider?

1)   You do not need to develop your own provider if you want a private database for a particular application (this database would not be accessible to applications other than the one that created it).

2)   You however need a Custom provider to provide custom search suggestions in your own application system.

3)   You would also need a Content Provider to copy and paste complex data from your application to other applications.

What are the operations supported by a Content Provider?

Content providers support the following basic operations:

1)   Querying: Queries the Content Provider for all the objects, based on the specified URI.

2)   Delete: Deletes the specified objects from the database of a Content Provider.

3)   Update: Makes updates to the objects in the database.

4)   Insert: Inserts new object to the database.

Android tutorials for beginners: Content Provider

Steps to carry out an operation in Content Provider

Step 1: Accessing a Content Provider

ContentResolver client object is used to access data from Content Provider. It communicates with provider object, which in turn accepts the request to access data and returns the desired results. The data exchange interface provided by the provider and provider client object allows communication across different processes/applications.

The application that needs to access the database has to declare this and request permissions in its manifest file. This would be discussed in detail in our subsequent Android tutorials.

Content URI

Content URI is one of the arguments used to identify the data in a provider. It has four parts:

1)  Scheme: The scheme for content provider has a constant value: “content”.

2)  Authority: It is the symbolic name of the provider, and is unique for each one. This is how we single out the desired content provider from a list of so many.

3)  Path: Path helps distinguish the required data from the complete database. For instance, the Call Log Content Provider differentiates between Missed Calls, Received calls etc. using different paths.

4)  ID: It is not a mandatory component, and may not be present in the URI; but if present, it should be numeric. For instance, if you want to access a specific music file from your Media Content Provider, you would specify an ID as well.

The process

Using the provider authority, the ContentResolver identifies the correct content provider (as authority is unique for each content provider). Having done that, the path component of URI is used to select the correct (requested) data table. In case an ID is present, the provider would know what exact data is being requested.

Android Tutorial : Accessing the content provider

URI’s are of two types:

Android tutorials for beginners: URI types

Additionally, URIs can have limiting information as well.

Step 2: How to retrieve data from a Content Provider

Even though the ContentResolver has access to the data table now, it cannot retrieve the required data unless the application has “read access permission” for that particular provider. This permission is defined in the manifest file of each content provider.

All that an application (that wants to access this database) has to do is to request this permission.

Now as discussed earlier in this Android tutorial, four operations can be carried out using a content provider. We will go over each one by one.

QUERYING

Now, you have accessed the provider, and have permission to retrieve data from it. The next step is to construct the query to request the required action from the provider.

Here are the arguments used while querying:

1)   URI: It works exactly as explained above.

2)  Projection: The query should return a set of columns from the entire database table. This is known as projection. Passing null will return all columns, which is inefficient.

3)  Selection Clause: A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URI.

For instance, if you enter an alphabet (say ‘P’) in the search column of your address book, then it would return all the contact details starting with ‘P’. However, if you do not enter anything in the search bar, the complete list of contacts is retrieved (the selection clause is set to ‘null’ in such cases).

4)  Selection Argument: You may include “?s” in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection.

5)  SortOrder: SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will fetch the results which may be unordered.

CODE EXAMPLE for Querying:

  • Searching for Phone numbers in Contacts
Cursor cursor = contentresolver.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
int count = cursor.getCount();

if (count > 0) {
String contactDetails = "";
	while (cursor.moveToNext()) {
		String columnId = ContactsContract.Contacts._ID;
		int cursorIndex = cursor.getColumnIndex(columnId);
		String id = cursor.getString(cursorIndex);
		String name = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
		int numCount = Integer.parseInt(cursor.getString(cursor
			.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
		if (numCount > 0) {
			Cursor phoneCursor = contentresolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
				CommonDataKinds.Phone.CONTACT_ID+" = ?", new String[] { id
}, null);

				while (phoneCursor.moveToNext()) {
				String phoneNo = phoneCursor.getString(phoneCursor
.getColumnIndex(ContactsContract.CommonDataKinds.
Phone.NUMBER));

					contactDetails += "Name: " + name + ", Phone No: "
								+ phoneNo + "\n";

					}

					phoneCursor.close();
				}
			}
		}

INSERTION

Let us suppose you want to insert new contacts to your address book. ContentValues object is used to do these insertions. The ContentValue object keys and the Content Provider columns must match to achieve this. Here’s an example for this:

CODE EXAMPLE FOR Insertion :

  • The operation is to insert new entry with name “Rajnikant” and number “9988999888”
// Operation
ArrayList ops = new ArrayList();
int rawContactInsertIndex = ops.size();

ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
	.withValue(RawContacts.ACCOUNT_TYPE, null)
	.withValue(RawContacts.ACCOUNT_NAME, null).build());

ops.add(ContentProviderOperation
	.newInsert(Data.CONTENT_URI)
	.withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
	.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
	.withValue(StructuredName.DISPLAY_NAME, “Rajnikant”).build());

ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
	.withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
	.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
	.withValue(Phone.NUMBER, “9988999888”)
	.withValue(Phone.TYPE, Phone.TYPE_MOBILE).build());

getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

UPDATING

To update a content provider the following arguments are used:

1)   URI: The URI of the Content Provider

2)  ContentValues: This contains the values that would replace the existing data.

3)  Selection Clause: This can help select the specific records to update

4)  Selection Argument: You may include “?s” in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection.

Once again, the keys of the ContentValues object must match the columns in the Content Provider; otherwise, the update would not occur.

CODE EXAMPLE FOR Updation:

  • Updating the phone number where name is “Rajnikant”
String where = ContactsContract.Data.DISPLAY_NAME + " = ? ";
String[] params = new String[] { “Rajnikant” };

ArrayList ops = new ArrayList();

ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
	.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, “9876543210”)
.build());

getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

DELETION

Deletion uses the same arguments as update; with the exception of ContentValues argument, which is not required as there will not be any substituted values.

CODE EXAMPLE FOR Deletion:

  • Delete the Contact where name is “Rajnikant”
String where = ContactsContract.Data.DISPLAY_NAME + " = ? ";
String[] params = new String[] { “Rajnikant” };

ArrayList ops = new ArrayList();
ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
	.withSelection(where, params).build());

getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

In case of Insert operation, the URI must be directory based. In all the other cases, the URIs can be either ID based or directory based.

We hope Android tutorial for beginners: Part 5 wasn’t too difficult to understand! We shall discuss more about Content Providers in Subsequent Android Tutorials. Enjoy learning the basics till then!

Do you have any doubts in this Android tutorial? Ask Us.

Happy Learning!

Following resources were used in creating this Android Tutorial! Official Android Developers, Edureka.in

You may also like these related posts:

Share on
Comments
28 Comments
  • Chrys

    What is the reuse policy on this site? You guys have such cool examples. Is your code available for reuse via Creative Commons? I’d really love to include some of your code examples in a textbook I am writing for Android beginners. Please advise. Thanks, Chrys

    • EdurekaSupport

      Hi Chrys, you can use the information in this blog post, provided you give due credit to Edureka.

24 X 7 Customer Support X

  • us flag 1-800-275-9730 (Toll Free)
  • india flag +91 88808 62004