Content Providers in Android

Content Provider in Android is a component of the Android application that is useful for sharing data with other apps. A content provider in Android is like a central repository of the Android application that stores the data and allows other apps to securely access and modify it based on the user requirements.

Let’s understand the content provider with an example: when you install WhatsApp on your Android device, it automatically fetches all the contacts that are using WhatsApp from your device’s contact app. So how exactly is WhatsApp doing that? 

Here, WhatsApp uses the content provider that is placed inside the system’s default contact app to fetch all the contacts that are using WhatsApp.A similar use case is when you are developing a calendar application, you might want to access the shared pool of calendar events that are saved on the device so every calendar app on the device can get access to the same pool of events. So Content Provider in Android is a wrapper around your Data Source (SQLite, Files, Cloud) that is used to share data between applications. 

Content providers in Android can store data in different ways, like in an SQLite database,
internal storage, external storage, or on the cloud (via network). Content Providers use content URI (Uniform Resource Identifier) to share data between applications.

Content URI (Uniform Resource Identifier)

Content URI (Uniform Resource Identifier) is a query string that is used by content providers to share data between applications. 

Structure of Content URI
				
					 content://authority/specificData/optionalID 
				
			
  • content:// -> The first part “content://” is prefix, It is standard way to start Content URI in Android
  • authority -> The second part is an authority, It’s a unique identifier for content provider.
  • specificData -> It’s a string that identifies exactly what data to access.
  • optionalID -> It’s a numeric value to access a specfic record from a specificData.                  
Example of Content URI
Content Provider Example Image
URI Example that points to a particular record in the table:
Content Provider Example Image

Operations in Content Provider

Four basic operations in content provider are as follows CREATE, READ, UPDATE, And DELETE.
In short, they are called CRUD operations.   

Operations Description
CREATE
Add a row or rows to the data
READ
Read from the available data
UPDATE
Update the data
DELETE
Deletes the row or rows from the data

How Content Provider Works?

Content Provider in Android sends a request to CursorLoader, and CursorLoader then sends a request to the ContentResolver object. The ContentResolver object sends requests to the ContentProvider as a client. ContentResolver is a class that provides applications access to the content model and also manages all the IPC (Inter-Process Communication). 

How Content Provider works in android

How to Create a Content Provider?

A content provider in Android is created by extending a class using
the base ContentProvider class. 

Following are the steps to create a content provider:

  • Create a class extending a base ContentProvider class.
  • Define a content provider URI address.
  • Implement the six abstract methods of the ContentProvider class.
  • Register the content provider in the AndroidManifest.xml file using the <provider> tag.

onCreate(), insert(), query(), update(), delete(), and getType() are the six abstract methods that are necessary to override to create a custom content provider. Let’s understand each methods: 

  • insert(Uri uri, ContentValues contentValues): This method inserts a new row into the provider and returns a content URI for that row. This method takes two arguments the first is URI and the second is contentValues.URI is used to select the destination table and ContentValues are used to insert data in the table same as in SQLiteDatabase.
  • query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder): This method Retrieves data from your provider and Returns the data as a Cursor object. This method has five arguments let’s understand what it is used for: 


    Uri-> 
    Uri is to select the destination table.

    projection-> 
    Projection is a string array that specifies which columns of the data should be returned. If the projection is null, all columns are returned.

    selection-> selection specifies the criteria for selecting rows. It ‘s condition for selecting rows.

    selectionArgs->
    Selection arguments specifies selection arguments in the form of the array. For example, if selection is “city = ?” and selectionArgs is {“Delhi”} then this would match rows where the city column is set to Delhi. selectionArgs will replace “?” in selection.

    sortOrder->
     sortOrder specifies the order in which rows appear. 

  • update(Uri uri, ContentValues contentValues, String selection, String[] selectionArgs): This method updates row or rows in the provider and returns the number of rows updated. This method has four arguments let’s understand each and it’s use case: 

    Uri-> Uri is to select the destination table.

    ContentValues-> ContentValues are similar to an Associative array or HashMap Where we can put key-value pairs. To provide updated data we use ContentValues.

    selection-> selection specifies the criteria for updating row or rows. It’s a condition for updating rows.

    selectionArgs-> Selection arguments specify selection arguments in the form of the array. For example, if selection is “city = ?” and selectionArgs is {“Delhi”} then this would match rows where the city column is set to Delhi and update only rows where the city column is set to Delhi. selectionArgs will replace “?” in selection.

  • delete(Uri uri, String selection, String[] selectionArgs): This method delete rows from the provider and returns the number of rows deleted.

    Uri-> Uri is to select the destination table.

    selection-> 
    selection specifies the criteria for deleting row or rows. It’s a condition for deleting rows.

    selectionArgs-> Selection arguments specify selection arguments in the form of the array. For example, if selection is “city = ?” and selectionArgs is {“Delhi”} then this would match rows where the city column is set to Delhi and deletes the rows where the city column is set to Delhi. selectionArgs will replace “?” in selection.

  • getType(Uri uri)-> This method Return the MIME type corresponding to a content URI and takes Uri as a parameter. For more details: content provider MIME types

Now Let’s Implement Content Provider in a code

Step by Step Code Implementation of ContentProvider

In this example, we will First Create a NotesApp using SQLiteDatabase and we will also create a ContentProvider to expose our notes data to other applications. In our second app, we will fetch and display all the notes data that is exposed by our first app using a content provider. 

Let’s start by creating our first app, which will contain SQLiteDatabase to store the data and A NotesProvider to expose our notes data to other application.

File: DBHelper -> which contains logic to store our notes data in SQLiteDatabase in Android          

Next is a NotesProvider class, which is used to expose Notes data to other applications. In here, the NotesProvider class will expose notes data for the client note app.

MainActivity contains the logic for adding the notes in the DB, and it also has a ReadNotes button, which will open another activity where we will fetch all the notes from the DB using the fetchAllNotes() function of the DBHelper.

File : activity_main.xml

File: MainActivity class java/kotlin

AllNotesActivity is used to show all the notes using ListView

File: activity_all_notes  

To show notes data in ListView, we have created a custom view and a Note Adapter to populate data on the ListView.

File: notes_view.xml


File: NotesAdapter class java/kotlin


File: AllNoteActivity class file kotlin/java

Now, we need to register our ContentProvider in The AndroidManifest file. So that other applications can access our ContentProvider. 

First, we need to create a permission for our ContentProvider based on that permission other applications can access our ContentProvider.  

We also need to register our content provider using the <provider> tag. 

SecondApp (ClientNotesApp) will display the notes using our NotesProvider 

In the MainActivity of the second app, we will display notes fetched by querying NotesProvider. We have implemented ListView to display notes.      

activity_main.xml

For the ListView We have created a custom view and adapter which are as follows:

File: notes_view

File: NotesAdapter Kotlin/Java

File: MainActivity class File Kotlin/Java

In, NotesDetailActivity of the second app we have displayed notes data in detail and from NotesDetailActivity we can also update and delete the note by using update() and delete() methods of ContentResolver object  

File: activity_notes_detail.xml

File: NotesDetailActivity File Kotlin/Java

We also need to get permission to access ContentProvider from this app. Don’t forget to add it to your client-side app.

Output:

Download the final project for ContentProvider in Android: Kotlin|Java