Reputation: 19937
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!
Upvotes: 7
Views: 6763
Reputation: 21
Since both your apps are running you can also solve this problem by setting shared preferences:
tempContext.getSharedPreferences("sharedInformation", Context.MODE_MULTI_PROCESS);
Upvotes: 0
Reputation: 39
Solved by just reading the old context again. Sounds like a cache to me too.
Context tempContext = context.createPackageContext(originalContext.getPackageName(),Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedInformationM2 = tempContext.getSharedPreferences("sharedInformation", Context.MODE_WORLD_READABLE);
Upvotes: 2
Reputation: 19937
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.
Upvotes: 2
Reputation: 721
You might want to make the SharedPreference created in App A MODE_WORLD_READABLE and use a common sharedUserId for both App A and App B. Like mentioned in the link,
http://androiddhamu.blogspot.in/2012/03/share-data-across-application-in.html
Upvotes: 1