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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With