Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read other app's SharedPreferences (same user ID)?

Tested on Android 4.3. I have two apps, com.my.app.first and com.my.app.second. In my activity I want to read preferences from the other app. I chose to use the same user ID for both my apps:

android:sharedUserId="com.my.app"

I always load my preferences like this:

prefs = getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE);

Now, in my second app I do the following:

try {
    Context context = createPackageContext("com.my.app.first", Context.CONTEXT_IGNORE_SECURITY);
    // context.getPackageName() does indeed return "com.my.app.first"

    // Note: Context.MODE_WORLD_READABLE makes no difference here!
    prefs = context.getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE);
}

prefs.mFile erroneously points to /data/data/com.my.app.second/shared_prefs/MyAppPreferences.xml.

Obviously, the call to getSharedPreferences returns the preferences for the current app even though I used the context of the other app. What am I doing wrong? Please help!

like image 367
l33t Avatar asked Aug 19 '13 12:08

l33t


1 Answers

Found the problem! This sure looks like a bug in the getSharedPreferences API. It turned out that a previous call to getSharedPreferences caused the other context.getSharedPreferences() call to return the previous instance - the current app's preferences.

The solution was to make sure that getSharedPreferences() was NOT called before reading the preferences of the other app.

like image 106
l33t Avatar answered Oct 05 '22 20:10

l33t