Content Provider

What is Content Provider?

When one application, wants to use the data provided by the other application then Content Provider comes into the picture.

image.png

Content Provider, provides data of one application to others on request.

Such requests are handled by the methods of the ContentResolver class.

A Content Provider uses different way to store its data. Data can be stored on Database, File or over the Network as well.

Android Device itself provides some native Content Providers, such as

Media Store: It is used for accessing the Photos and Videos from the gallery.

User's Contact List: Accessing user's contact list.

Possible Operations in Content Providers:

Total 4 operations are possible using Content Providers. They are often termed as "CRUD" operation.

C: Used to create data in CP

R: Read data in CP

U: Updating existing data in CP

D: Deleting Data from CP

Typical Content Provider URI:

content://student/attendance/12
  1. content:// -> It is a mandatory part of the URL, it identifies that given URL is a Content URL.

  2. Authority -> In our case, authority is a student. It is a name of Content Provider. For different Content Provider, you shall use different names. Sometimes Authorities are package name, like -> com.demo.tushar.provider

  3. optionalPath -> attendance is an optionalPath, it denotes the type of data provided by the Content Provider.

  4. optionalID: 12 is an optional ID. In our example, we are trying to fetch attendance of student whose id is 12.

If you wish to use the CP in application, you must provide necessary information in the provider of the manifest file.

How to use Content Provider in the application?

First, create a file named CP.java where your MainActivity.java resides.

Then, create a class named CPDemo which extends ContentProvider class.

Below, is an example of Content Provider.

public class CPDemo extends ContentProvider{
    // here you should implements the methods which are necessary. 
}

Methods of Content Provider class.

  1. onCreate(): When the Content Provider is created. This method is called immediately.
  2. query(): This method is used to retrieve data from Content Provider, data are returned as a cursor object.
  3. insert(): Self - Explanatory
  4. update(): Self - Explanatory
  5. delete(): Self - Explanatory