Android Content Providers
Android Content Providers facilitate sharing data between different applications by managing a specific type of data that can be queried, inserted, updated or deleted.
It acts as an interface between the data source and the application that requires the data, thus ensuring secure and safe data sharing.
Content Providers provide a common interface to access data stored in databases, files or on the internet.
Accessing a Content Provider requires knowing the URI (Uniform Resource Identifier) of the provider, which consists of the authority of the provider and the path to the data.
Android provides built-in Content Providers such as Contacts Provider, Media Provider, and Call Log Provider, while developers can also create their own Content Providers to share data between their applications or with other applications.
Creating a Content Provider
Developers must extend the ContentProvider class and implement several methods to create a Content Provider.
Using these methods, you can manage the data source, handle queries, insert, update, and delete data.
The following methods can be implemented on a content provider:
Methods | Overview |
onCreate() | When the Content Provider is created, this method is called. It creates the data source. |
query() | An application calls this method when it requests data from the Content Provider. The data is returned as a Cursor object. |
insert() | The insert() method is called when an application wants to insert data into the Content Provider. The newly inserted data’s URI is returned. |
update() | The update() method is called when an application wishes to update the Content Provider’s data. The number of rows affected by the update is returned. |
delete() | Application calls this method to delete data from the Content Provider. The number of rows affected by the deletion is returned. |
getType() | Returns the MIME type of the data managed by the Content Provider. |
Here’s an example of a simple Content Provider that manages a list of books.
Define the contract class:
public final class BookContract { // Authority for the Content Provider public static final String AUTHORITY = "com.example.bookprovider"; // Base URI for the Content Provider public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY); // Path for the books table public static final String PATH_BOOKS = "books"; public static final class BookEntry implements BaseColumns { // URI for the books table public static final Uri CONTENT_URI = BASE_URI.buildUpon().appendPath(PATH_BOOKS).build(); // Table name public static final String TABLE_NAME = "books"; // Column names public static final String COLUMN_TITLE = "title"; public static final String COLUMN_AUTHOR = "author"; public static final String COLUMN_PRICE = "price"; } }
Create a SQLite Database:
public class BookDatabase extends SQLiteOpenHelper { private static final String DATABASE_NAME = "books.db"; private static final int DATABASE_VERSION = 1; public BookDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // Create the books table String CREATE_BOOKS_TABLE = "CREATE TABLE " + BookContract.BookEntry.TABLE_NAME + "(" + BookContract.BookEntry._ID + " INTEGER PRIMARY KEY," + BookContract.BookEntry.COLUMN_TITLE + " TEXT," + BookContract.BookEntry.COLUMN_AUTHOR + " TEXT," + BookContract.BookEntry.COLUMN_PRICE + " REAL" + ")"; db.execSQL(CREATE_BOOKS_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Upgrade the database schema db.execSQL("DROP TABLE IF EXISTS " + BookContract.BookEntry.TABLE_NAME); onCreate(db); } }
Create the Content Provider:
public class BookProvider extends ContentProvider { private static final int BOOKS = 1; private static final int BOOK_ID = 2; private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sUriMatcher.addURI(BookContract.AUTHORITY, BookContract.PATH_BOOKS, BOOKS); sUriMatcher.addURI(BookContract.AUTHORITY, BookContract.PATH_BOOKS + "/#", BOOK_ID); } private BookDatabase mDatabase; @Override public boolean onCreate() { mDatabase = new BookDatabase(getContext()); return true; } @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String
The “UserContract” class defines the contract for the data managed by the Content Provider.
The “UserProvider” class extends the “ContentProvider” class and implements methods for performing CRUD operations on the data.
The class is also registered in the AndroidManifest.xml file. In the MainActivity, a ContentResolver object is obtained and used to perform a query operation on the Content Provider by creating a Uri object with the Content Provider URI and calling the query() method. The result is then displayed in a TextView.
Android Content Provider Registeration
A Content Provider must be registered in the AndroidManifest.xml file before it can be used by other applications.
Registration includes the authority of the provider and the path to its data.
Following example defines the syntax of registering a content provider:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapp"> <application android:name=".MyApplication" android:icon="@drawable/app_icon" android:label="@string/app_name"> <provider android:name=".MyContentProvider" android:authorities="com.example.myapp.provider" android:exported="true"/> ... </application> </manifest>
Define the provider in the AndroidManifest.xml file using the <provider> element. The following attributes need to be set
- android:name: The fully qualified name of the Content Provider class.
- android:authorities: A unique string that identifies the Content Provider to the Android system.
- android:exported: Whether other applications can access the Content Provider. Set it to true if you want other applications to access it.
Accessing a Content Provider
In order to access a Content Provider, an application needs its URI.
The application can access the provider using a ContentResolver object once it has obtained the URI.
To access a Content Provider, follow these steps:
- Get a ContentResolver object by calling getContentResolver().
- A Uri object is created with the URI of the Content Provider.
- Using the ContentResolver object, call the appropriate method to perform the operation (query, insert, update, delete).
Assume that we have created a custom Content Provider that provides information about books.
The provider has a URI of “content://com.example.booksprovider/books” and has the following columns: “_id” (book ID), “title” (book title), and “author” (book author).
To retrieve all the books from the provider, we can use the following code:
// Step 1: Get a ContentResolver object ContentResolver resolver = getContentResolver(); // Step 2: Create a Uri object with the URI of the Content Provider Uri uri = Uri.parse("content://com.example.booksprovider/books"); // Step 3: Call the query() method on the ContentResolver object to retrieve all books Cursor cursor = resolver.query(uri, null, null, null, null); // Iterate through the cursor to retrieve the book information if(cursor != null && cursor.getCount() > 0) { while(cursor.moveToNext()) { int bookId = cursor.getInt(cursor.getColumnIndex("_id")); String bookTitle = cursor.getString(cursor.getColumnIndex("title")); String bookAuthor = cursor.getString(cursor.getColumnIndex("author")); // Do something with the book information } } // Close the cursor if(cursor != null) { cursor.close(); }
In this example, the first step is to obtain a ContentResolver object by calling the getContentResolver() method. Then, a Uri object is created with the URI of the Content Provider (“content://com.example.booksprovider/books”).
After that, the query() method is called on the ContentResolver object to retrieve all the books. The query() method returns a Cursor object that contains the book information. The cursor is iterated through to retrieve the book information using the getColumnIndex() method.
Lastly, the cursor is closed to release the resources.