Content Provider in Android
A content provider in Android comprises access to a central repository of data, that can be stored in a variety of ways like SQLite database, a file, or a web service. To access the data, a unique Content URI associated with the provider will be used. It acts as an abstraction layer over the underlying data storage mechanism, allowing other apps to interact with the data using content URIs.
A content provider in Android is among the fundamental components of the Android operating system (along with services, activities, and broadcast receivers).
With the help of a content provider, an application can make data available to other applications without exposing the implementation of it. This makes data sharing more secure and also provides better control over it. The Android operating system provides numerous built-in content providers, but developers can also create their own custom providers to expose and control the data that has to be shared with other applications.
What are Content Providers in Android?
Have you ever wondered how your favorite Android apps can easily access and share data with each other? The answer lies in content providers - a crucial component of the Android operating system.
They are the fundamental components of the Android operating system and provide a standardized way for the applications to share and access data with each other. In other words, they act as a binding bridge between the data storage and the user interface of the application.
A content provider in Android can help in securely sharing the data between applications by providing a layer of abstraction. A set of CRUD (Create, Read, Update, Delete) operations are exposed that can be performed on the data and the applications can access the data from various sources like a database, a file, or a web service.
CRUD Operations
Create
This operation is used to insert new data into a content provider. It is implemented using the insert() method of the content provider.
-
Explanation
ContentValues is a class that allows you to store a set of key-value pairs, where the key represents the column name in a database table, and the value represents the corresponding data to be stored in that column.
Read
This operation is used to retrieve data from a content provider. It is implemented using the query() method of the content provider.
-
Explanation
The query() method comprises several parameters (Content URI, values, selection, selectionArgs) that have been set to null in our example. All these parameters would be explained in the upcomig section.
Update
This operation is used to modify existing data in a content provider. It is implemented using the update() method of the content provider.
Delete
The delete operation will remove data from a content provider. It is implemented using the delete() method of the content provider.
The delete() method also returns the number of rows deleted from the table.
Examples of Android Content Providers
Content Provider in Android can be further categorized into:
- Built-in content providers
- Third-party content providers
Built-in Content Providers in Android
-
ContactsContract:
This built-in content provider is used to provide access to the device's contact data such as a phone number or an email address.
-
MediaStore:
This built-in content provider is used to provide access to the device's media files such as videos, photos, and also audio recordings.
-
Calendar:
It provides access to the device's calendar data.
-
UserDictionary:
Provides access to the user dictionary data (stores custom words that can be used by the keyboard app for suggestions).
Popular Third-party Content Providers
-
Firebase Realtime Database:
It's a cloud-based NoSQL database that provides real-time data synchronization across multiple devices.
-
SQLite:
It's a database engine for Android that provides a lightweight and efficient way to store and retrieve data.
-
Google Drive:
Google Drive is a cloud-based file storage and sharing service that provides access to files from anywhere and on any device.
-
Twitter API:
Twitter API provides access to Twitter data, such as tweets, mentions, and direct messages.
Other examples of popular third-party content providers are Dropbox, Microsoft OneDrive, and Amazon S3.
Accessing Data with Content Provider
There are a few key steps to accessing the data with the help of a content provider in Android. It involves determining the Content URI, obtaining a ContentResolver instance, and then using the appropriate CRUD operations to manipulate the data.
Determine the Content URI
A content URI is a unique identifier that indicates the data to be accessed, usually in the form of content://AUTHORITY/path/id . Here, the AUTHORITY is the content provider's unique identifier, while the path and id are the parameters that identify the data to be accessed.
An Instance of ContentResolver
We need to create an object of ContentResolver to provide access to content providers in Android. It can be obtained using the context object in this manner: ContentResolver cr = context.getContentResolver();
Query the Content Provider
Querying the Content Provider in Android can be done using the ContentResolver's query() method. This would require the following parameters:
- Content URI
- projection (the columns to be returned)
- selection (criteria for selecting the data)
- selectionArgs (arguments for the selection criteria)
- sortOrder (sorting order for the returned data)
- Cancellation signal (in order to cancel the operation, if needed)
The query method returns a Cursor object, which can be used to iterate through the returned data.
Insertion of the Data
The data can be inserted using the insert() method of the ContentResolver, which takes in the Content URI and a ContentValues object that contains the data to be inserted.
Updating the Data
To update the data, we can use the insert() method of the ContentResolver, which takes in the Content URI and a ContentValues object that contains the data to be inserted.
Deleting the Data
Deleting the data requires the delete() method of the ContentResolver that requires the parameters such as Content URI, selection criteria, and selectionArgs.
Methods of Content Provider in Android
onCreate()
The onCreate method in the content provider is called during the creation of the content provider in Android. It is responsible for initializing essential resources, such as a database, and returns a boolean value to indicate the success of the initialization process.
Here's an implementation of the onCreate() method:
query()
The query() method is another fundamental method in an Android content provider that handles data retrieval operations. It is responsible for querying the data source of the Content Provider and returning the requested data as a Cursor object. Other apps can use this method to fetch data from the content provider in Android.
Let's understand all its parameters:
-
Uri uri:
The URI that specifies the data to be queried. The content provider can interpret different parts of the URI to determine the appropriate data to retrieve.
-
String[] projection:
An array of column names that specifies which columns of the data should be included in the result. If null is passed, all columns will be included.
-
String selection:
A selection criteria that filters the rows to be returned. It can include placeholders for selection arguments.
-
String[] selectionArgs:
An array of selection arguments that replace the placeholders in the selection criteria.
-
String sortOrder:
The sorting order for the result rows. It specifies the column(s) and the sorting order (ascending or descending).
Here's the implementation for the query() method:
Explanation
Here, we have also provided different ids to fetch a single row as well as all the rows.
The method uri.getLastPathSegment() will update the selection arguments with the last path segment of the URI, which represents the row ID.
The cursor.setNotificationUri() method sets the notification URI for the Cursor object to enable automatic updates when there's a change in the queried data.
insert()
The insert() method in an Android content provider is responsible for inserting new data into the database or any other data source of the Content Provider in Android. Other apps can also use this method to add new data to the content provider.
Explanation
The statement SQLiteDatabase db = dbHelper.getWritableDatabase(); gets a reference to the database where we need to insert the data. The getWritableDatabase() method creates the database if it does not already exist, and returns a reference to it.
The long id = db.insert(TABLE_NAME, "", values); comprises three different parameters. The second parameter "" is actually a reference to the column of the table where we want to insert the data. The third parameter is the ContentValues object that contains the values we want to insert.
We use the ContentUris.withAppendedId() method to add the ID of the new row to the end of the uri parameter that was passed in.
The notifyChange() method sends a notification and allows the UI component to update themselves with the new data.
update()
The update() method is responsible for updating existing data in the database. Other apps can use this method to modify existing data in the content provider.
delete()
The delete() method deletes the data from the data source of the Content Provider in Android. The delete() method can also be used by other applications to remove the data from the content provider in Android.
getType()
The getType() method helps in retrieving the MIME (Multipurpose Internet Mail Extensions) type of the data associated with a given URI. The MIME type is a string that helps in identifying the format of the data that is being transferred between the apps. Content providers in Android use MIME types to describe the types of data they can provide or accept.
Explanation
Here, in our implementation, we have used uriMatcher to determine the type of the URI. There are three conditions to determine the MIME type.
- If the URI matches the ALL_ROWS case, then it would be referring to a collection of data and would return a MIME type starting with vnd.android.cursor.dir/.
- Alternatively, for the SINGLE_ROW case, since it is referring to a single row of data, so we'll have a MIME type beginning with vnd.android.cursor.item/.
- For the mismatch with both of these predefined cases, an IllegalArgumentException would be thrown.
In the above MIME types, the vnd prefix stands for vendor-specific. The part after the slash is used to identify the format of the data (com.example.myapp).
Content URIs
Content URI (Uniform Resource Identifier) is a unique identifier used to reference and access data within a content provider in Android. It is a standardized way to interact with the data managed by a content provider.
Content URIs comprise the following format: content://authority/path/id.
Details of Different Parts of the Content URI
Here's a breakdown of each of the components it uses:
content://
content://is the scheme that helps in identifying the URI as a content URI.
authority
It identifies the content provider in Android that manages the data. It's usually a package name of the app that provides the content provider. However, it could also be a unique identifier that an app developer is free to specify in his own way.
path (Optional)
It represents the type or category of the data being accessed. The path is a string that informs the content provider to determine the appropriate data source or the table to handle all the requests.
In some cases, the path my or may not be present as the authority alone is sufficient to perform any desired operation. As in the example, content://com.android.provider/songs is a reference to the songs table. However, we can just provide a reference as content://com.android.provider when we are referring to the entire content provider rather than a specific path or a table within it.
id (Optional)
The ID segment is used when we need to access a single item that can be identified by its unique ID. Moreover, it's optional and may or may not be present depending on any specific use case.
For example, we have a content URI content://com.android.provider/songs. The URI would be a reference to the songs table that is managed by the content provider of the app with the package name com.android.provider.
Now, if a URI is referencing a specific song, it would be something like content://com.android.provider/songs/12 where 12 can be the ID for a specific song.
Operations in Content Provider
Create
This operation is used to add new data from the data source of the content privider. It involves inserting a new row or record into a table or data collection using the insert() method of the Content Provider in Android.
Read
This operation is used to retrieve data from the data source of the content privider. It involves querying the data source based on specified criteria and retrieving one or more rows or records that match the criteria using the query() method of the Content Provider.
Update
The update operation modifies the existing data from the data source. It involves updating one or more rows or records with new values based on specified criteria by using the update() method of the content provider.
Delete
The delete operation removes the data from the data source of the content provider. Based on our specified criteria, it involves deleting one or more rows/records from the table.
Working of the Content Provider
As the final upshot, we can now illustrate all the components involved with the working of a Content Provider in Android.
- A Content Provider has to be defined by creating a user-specific class that extends the ContentProvider base class.
- The content provider should also be registered in the application's Manifest file by adding a <provider> element inside the <application> element.
- Now, determine the data source for the content provider. It can either be an SQLite database, a Room database, a file storage, or a network API.
- Define the content URIs that will be used to access different types of data within the content provider. Use a UriMatcher object to match incoming URIs with specific patterns.
- Implement the CRUD oprations by overriding the methods (query(), insert(), update(), delete()).
- Implement the getType() method to return the appropriate MIME type for a given content URI.
- To help other apps interact with the content provider, an object of the ContentResolver will be used.
Creating a Content Provider
Step 1: Create a New Project
Create a new project in Android Studio by selecting "Empty Activity" as the template.
Step 2: Modify the strings.xml File
Add the following string resources in the strings.xml file:
Step 3: Creating the Content Provider class
We need to create our own ContentProvider class with following code:
Explanation
We need to create a DatabaseHelper class that extends SQLiteOpenHelper and comprises methods to create and drop a table. It overrides the onCreate() and onUpgrade() methods for the same. The onUpgrade() method is used to drop the existing users table and create a new one if the database version is changed.
Step 4: Design the activity_main.xml Layout
Here's a simple layout for the activity_main.xml file that includes two EditText and two buttons to interact with the content provider:
Step 5: Modify the MainActivity File
Now, here's how you need need to implement the methods for data manipulation in your application.
Step 6: Modify the AndroidManifest File
To use the content provider in our app, we need to declare it in the AndroidManifest.xml file.
Add the following code inside the <application> tag:
Creating Another Application to Access the Content Provider
Step 1: Create a New Project
Create a new project in Android Studio by selecting Empty Activity as the template. You can choose the minimum SDK as per your wish.
Step 2: Modify the strings.xml File
Add the following string resources in the strings.xml file:
Step 3: Modify the activity_main.xml Layout
Step 4: Modify the MainActivity File
Step 5: Modify the AndroidManifest File
To facilitate the sharing of data from the previous application that we created, we need to provide its package name in the Manifest file inside the <queries> element.
Output:
Conclusion
- Content provider in Android system enables secure data sharing between applications, and provide a standardized interface for accessing and manipulating data.
- ContentValues is a class provided by Android that allows you to store a set of key-value pairs, where the key represents the column name in a database table, and the value represents the corresponding data to be stored in that column.
- Content Provider in Android can be further categorized into Built-in content providers and Third-party content providers.
- A Content Provider has to be defined by creating a user-specific class that extends the ContentProvider base class.
- CRUD operations (Create, Read, Update, Delete) are commonly performed using content providers to manipulate data stored in databases or other data sources.
- The core methods of a content provider include onCreate(), query(), insert(), update(), delete(), and getType().