Share SQLite database between 2 android apps?

UPDATE: The method described below relies on android:sharedUserId, deprecated as of API level 29 (Android 10).

You certainly can share a single database between 2 apps.

In order to share data between apps (provided they are issued by the same publisher) you will need to specify a shared user id in the AndroidManifest.xml of both apps.

<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:sharedUserId="my.app" ... >

(It’s undocumented, but the shared user id needs to be a string with at least one dot separator)

The rest is easy, and you don’t need to mess around with the database path. Just use the same DBAdapter in both apps. In the app that hosts the database, call the DBAdapter with the native context.

DBadapter hostDBAdapter = new DbAdapter(getApplicationContext());
performerDBadapter.open();

In the second app, access the database with the context of the database hosting app.
First, define the shared context:

Context sharedContext = null;
    try {
        sharedContext = this.createPackageContext("replace.with.host.package.name", Context.CONTEXT_INCLUDE_CODE);
        if (sharedContext == null) {
            return;
        }
    } catch (Exception e) {
        String error = e.getMessage(); 
        return;
        }   

Then open the DBAdapter with the shared context:

DbAdapter sharedDBadapter = new PerformerDbAdapter(sharedContext);
sharedDBadapter.open();

As a final note, if your database exists previous to setting the shared user id in the manifest, you will need to uninstall/reinstall the apps on a physical device, lest you will lock yourself out of your database (sqlite error 14). The emulator, on the other hand, might prove to be more forgiving. Bottom line, if your apps are published on the Android market, setting a shared user id in an afterthought will not work.

Hope this helps.

Leave a Comment