+1

How to Write a Content Provider

rsz_screenshot_from_2016-09-26_105039.png

What is Content Provider

Content providers are Android’s central components which allows you to access data of different applications. Generally, in the Android security model, one application can't directly access data of other application. Every application has its own protected data directory and memory area. In that case, ContentProvider is the best way to distribute data across applications.

A ContentProvider distributes data using request which is handled by the methods of the ContentResolverclass. The data can be stored in database, in files or even over a network.

Basic Operations

ContentProvider has 04 basic operations namely CRUD operations. CRUD is the acronym for Create, Read, Update & Delete.

rsz_2untitled_diagram.png

The above diagram shows how content provider actually works. Application-2 has it's own database & content provider. Application-1 communicates with the content provider to access Application-2's data with simple interfaces which uses query(), insert(), update() & delete() methods. So, it is easy to implement a content provider & it works like SQLite database but still there is a fundamental difference. Using SQLite you can't share data to other applications but using content provider you can!

URI as Content Identifier

A special URI starting with content:// will be assigned to each content provider and that will be identified in the applications. There are 04 fundamental parts in a URI as following:

URI format: content://authority/path/id where :

  1. content:// The content provider URI is started with this value.
  2. authority is actually the Java package name used in the Application.
  3. path is the virtual directory within the provider that acts as an identifier of the requested data.
  4. id is optional part that specifies the primary key of a record being requested. We can omit this part when we need to request all data.

The System Offered Content Providers

In Android system, there is a list of default content providers to access data like Calendar, Contacts, MediaStore, SMS, Call, UserDictionary, Settings etc. You can find a package-summary in the official page & use the following code-snap to see the available providers in your Android device.

 for (PackageInfo packageInfo : getPackageManager()
          .getInstalledPackages(PackageManager.GET_PROVIDERS)) {
      ProviderInfo[] providers = packageInfo.providers;
      if (providers != null) {
          for (ProviderInfo provider : providers) {
              Log.d("Content Provider ", "Authority: " + provider.authority);
          }
      }
  }

Query on Content Provider

To query on a content provider you need to do as following:

    mCursor = getContentResolver().query(
    mUri,                    // The content URI of table.
    mProjection,             // String array to point the columns in the query result.
    mSelectionClause         // String of selection criteria.
    mSelectionArgs,          // Argument string for selection.
    mSortOrder);             // The sort order of the query result.

Writing a Content Provider

According to the Android official document, you can decide if you need a content provider or not! Actually, when you want to share complex data & custom search suggestions then you may try it.

Now, there are the basic steps are describing about how to write your own content provider using the local database:

  • Step-1: Creating the provider with extending ContentProvider class.
  • Step-2: Creating the local database with extending SQLiteOpenHelper class. You may need the data model to pass contents among provider, local database & activities.
  • Step-3: Declare the content provider in the AndroidManifest file.

Basically, The ContentProvider class looks like following:

package com.licon.contentprovidersample;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.Nullable;

public class SampleContentProvider extends ContentProvider {

    public boolean onCreate() {
        return true;
    }

    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        // Content query goes here
        return null;
    }

    public String getType(Uri uri) {
        // Content type goes here
        return null;
    }

    public Uri insert(Uri uri, ContentValues values) {
        // Add new data here
        return null;
    }

    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // Delete data here
        return 0;
    }

    public int update(Uri uri, ContentValues values,
                      String selection, String[] selectionArgs) {
        // Update data here
        return 0;
    }
}

After creating necessary provider, local SQLite database, model & other contracts you need to declare the ContentProvider into AndroidManifest file as following:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.licon.contentprovidersample">

    <application
        .... >
        ....

        <provider android:authorities="com.licon.contentprovidersample.provider"
            android:name="com.licon.contentprovidersample.SampleContentProvider"
            android:label="@string/provider_name"
            android:exported="false"/>
    </application>

</manifest>

If your content-provider is ready then you can use it with the CRUD operations like query(), insert(), update() & delete(). You may look the sample content-provider in the following link: https://github.com/liconrepo/AndroidContentProvider

References

Now, it's your time to make the content provider to share data to others. Happy Coding!


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí