Content Provider – Android Development Tutorials | Articles

The Content Provider provides content to the Android application. They are one of the primary building blocks of Android applications.

You need to use Content providers only if data needs to be shared between multiple applications. For example, the contacts information needs to be shared among multiple applications so it will require content providers.

Content providers encapsulate data and provide it to applications through the single ContentResolver interface.

Steps to create ContentProvider

  1. Create ContentProvider subclass (android.ContentProvider)
  2. Register ContentProvider in AndroidManifest.xml file using provider element. (<provider>).

 

To Register ContentProvider use following attributes:

  • android:name -> ContentProvider subclass name.
  • android:authorities -> authority used for ContentProvider
  • android:exported -> true/false (If true: ContentProvider can be used in other applications/ If false: Content provider is used only in local application)

 

The default value of android:exported is “true”.

URI

URI stands for Universal Resource Identifier.

  1. URI is used to identify a ContentProvider uniquely in the current device.
  2. URI has a special format like Content://Authority/Path 

 

Format contents are explained below:

Content: It is the protocol used to communicate ContentProvider.

Authority: A unique identifier used to identify ContentProvider (generally Authority is the name of the package in which ContentProvider is registered).

Path: It is a unique string appears after authority which is used to identify the table used in operation.

We can create our own ContentProvider by creating the subclass of ContentProvider and extends with ContentProvider and using a database like SQLite database and its methods.

Some primary Content Provider methods are

onCreate():  This is called to initialize the provider.

query(Uri, String[], String, String[], String):  It returns data to the caller.

insert(Uri, ContentValues):  It inserts new data into the content provider.

update(Uri, ContentValues, String, String[]):  It updates existing data in the content provider.

delete(Uri, String, String[]):  It deletes data from the content provider.

getType(Uri):  It returns the MIME type of data to the content provider.

Declare the ContentProvider in AndroidManifest.xml file

Initialize ContentProvider and Database

Use URIMatcher class to know the type of URI, URIMatcher matches the patterns.
Now further you can implement your methods in this class.

Team RCV Academy

About Team RCV Academy

RCV Academy Team is a group of professionals working in various industries and contributing to tutorials on the website and other channels.

View all posts by Team RCV Academy