Sharing data between your Apps on Android using Content Provider

Hello in this blog post we are going to talk about how you can share database or files between your apps on Android. This situation can be useful if for e.g, you have Widget App and another Launcher App which need to share same database. Or you have many applications which need consume similar set of data. Another possible scenario is if you want to share some important data which resides in your application to any other apps who may need it. You may already be consuming data from other apps (e.g, from Android OS, to access contacts, media files or calendar events). For all of the above scenerios, the Android SDK came up with “ContentProvider” as a solution.

ContentProvider is appropriate when you want to share your database or flat files between Android apps. Under the hood, Content Provider will a set the implementation for performance and security optimization. On implementation level, of the ContentProvider abstract class, we will need to override required abstract methods to provide our own implementation on how to perform CRUD operation (create, read, update, delete operation) . And our ContentProvider can be consumed through ContentResolver. I will provide you the full source and in the blog post I will go through the concepts and implementations.

Creating your own Provider to share database

In our example, we have an app which wants to share an SQLite database to other apps. We will do so by creating our own Content Provider share the “Phonebook” table. The Phonebook table contains person’s name and their corresponding phone number. I will assume you already know how to setup SQLite database here.

ContentProvider – Abstract methods to be implemented

ContentProvider is an abstract class and we will be required to implement the following methods to allow other consumers to access/update our PhoneBook table:

  • OnCreate() method – Prepares the content provider

In the OnCreate method, we can create an instance of our SqliteDatabase such that other methods will get an instance of dbManager to insert/delete/update objects.

private SqliteDatabaseManager dbManager;
@Override
public boolean onCreate() {
 dbManager = new SqliteDatabaseManager(getContext());
 return false;
}
  • getType() – Returns the MIME type for this URI
  • query() method – For any Query request
public Cursor query(@NonNull Uri uri, String[] projections, String selection, String[] selectionArgs, String sortOrder) {
}
  • insert() method – inserting into the Phonebook table. ContentValues will contain the data to be inserted. E.g, person’s name and phonenumber
@Override
public Uri insert(Uri uri, ContentValues contentValues) {
}

Inside the insert method, we can insert the data into SQLite database.

  • delete() method – deleting object from Phonebook table
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
}
  • update() method – updating object from Phonebook table
@Override
public int update(Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) {
}

Important methods:

URIMatcher – To deal with multiple URIs Android provides the helper class UriMatcher – https://developer.android.com/reference/android/content/UriMatcher.html

Contract Class – ContractPhonebook class

This class that we coded is also known as a contract class. A contract class explicitly specifies the schema (how a database and its tables are organized).

Exposing our ContentProvider – AndroidManifest.xml

We will need to declare “Provider” element to expose our ContentProvider inside the application tag in our AndroidManifest.xml file:

Refs: https://developer.android.com/guide/topics/manifest/provider-element.html

<permission android:name="com.devanshapps.programmingreferences.READ_DATABASE"
    android:protectionLevel="normal" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name="com.devanshapps.programmingreferences.MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <provider
        android:authorities="com.devanshapps.programmingreferences.Phonebook"
        android:name="com.devanshapps.programmingreferences.PhonebookProvider"
        android:permission="com.sqisland.android.protected_provider.ACCESS_DATA"
        android:exported="true"/>
</application>

Noticed that we have created our Permission with protectionLevel = “signature”:

<permission android:name="com.devanshapps.programmingreferences.READ_DATABASE"
    android:protectionLevel="signature" />

So any other apps which want to access our ContentProvider will get this permission. With android:protectionLevel=”signature”, we will only allow applications which use the same “keystore” to be able to obtain this permission. Basically we will have this permission if we want to limit access to e.g, only our own applications signed with same Keystore.

Using ContentResolver to insert data

String AUTHORITY = "com.devanshapps.programmingreferences.Phonebook";
String PATH  = "/phonebook";
Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + PATH);
ContentValues values = new ContentValues();
values.put("person_name", "Devansh Ramen");
values.put("phone_number", "12300000");
Uri mUri = getContentResolver().insert(CONTENT_URI, values);

The ContentProvider can be accessed with any other applications such that we are able to perform CRUD operation on the PhoneBook table.

Example Source code

Please find the full source code as discussed in the blog post on . github: https://github.com/devansh-ramen/Android-ContentProvider-Example

Conclusion

I hope you have learned when you will need to use Content Provider and how to create your own content providers or consume those from other apps on android. If you have any question or helpful information, we can “share” through the Comment Section below! 😉 Please subscribe for more post. Catch you in next one!! Happy coding

Reference:

https://developer.android.com/guide/topics/providers/content-provider-creating.html

Please Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s