Android tutorial – Shared Preferences Between Apps

Most of the time we will need to use shared preferences in our app in order to save some data locally. However, shared preferences can be used to make apps access each other prefs.
For example this can be useful if you are building a calendar and a reminder app. You set the events in calendar, and the reminder app will show you those events. One solution for this would be to send those events to a database and the reminder app to retrieve them, but what will you do if there is no internet connection? For this you can use shared preferences like this: save the events to shared preferences in the calendar app and after that, you will retrieve them in the reminder app.

So, how do we do this? First, we need to add “android:sharedUserId” to both of our apps, and it has to be the same in both of them. The manifest of calendar app will look like this:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.com.calendar"
    android:sharedUserId="whatever.string.you.want">

    <application
    	<!-- iada iada iada -->
    </application>

</manifest>

We also need to remember the package name from the manifest, because it will tell us from which app to get the shared prefs. In our case, the package name is “example.com.calendar”.

Let’s write some information in the shared preferences of the calendar:

		SharedPreferences prefs = getSharedPreferences("my.preferences", Context.CONTEXT_IGNORE_SECURITY);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("events", "event #1");
        editor.commit();

And this is how we retrieve the info in our reminder app:

		try {
            Context context = createPackageContext("example.com.calendar", 0);
            SharedPreferences pref = context.getSharedPreferences("my.preferences", Context.CONTEXT_IGNORE_SECURITY);
            String event = pref.getString("events", "No event for you");

            Log.i("sharedPref event", event);

            if(event == null || event.equals("")) {
	            pref.edit().putString("events", "why no events for me? :( ").commit();
            }

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

Some errors that you might encounter are:
-INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID – the shared user id is not written correctly, you can find solution here: http://stackoverflow.com/questions/15312330/installation-error-install-parse-failed-bad-shared-user-id
-INSTALL_FAILED_UID_CHANGED – you already builded the app using a shared user id, and you changed it, you need to uninstall the app and build again

Leave a Reply

You must be logged in to post a comment.