1

I'm working on a project where I have a core application and multiples plugins which are different apks. I would like to share some data between my different modules (for ex. the name of the user or his email address). I tried to give them all the same sharedUserId by adding it to their manifest :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.giom.mymodule1"
          android:sharedUserId="com.giom">

My modules are really similar and both save and try retrieve their sharedpreferences the same way :

Context mainAppContext = getActivity().getApplicationContext().createPackageContext("com.giom.mainapp", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
SharedPreferences sharedPreferences = mainAppContext.getSharedPreferences("sharedpreferences", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
sharedPreferences.edit().putString("EMAIL", email).commit();

And

Context mainAppContext = getActivity().getApplicationContext().createPackageContext
("com.giom.mainapp", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
SharedPreferences sharedPreferences = mainAppContext.getSharedPreferences("sharedpreferences", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
String email = sharedPreferences.getString("EMAIL", null)

Both codes are from my PreferenceActivities which are FragmentActivity. The problem is this seems to be working ; for example if I change the value in one of the modules and reboot the phone the other is changed. But if I open one of the activities, then the other, change the value in one of them and come back to the other I will still get the old one until I reboot. It's working like if there was some kind of cache...

My intuition is that I'm not using the right Context and that I should replace getActivity() by something else but I don't know what...

Thanks in advance for your help.

PS: I read that this method was depreciated so if you have any idea of how I should share my data feel free to tell me :)

Giom
  • 133
  • 10

1 Answers1

1

Ok, found the answer here : https://stackoverflow.com/a/11025235/3628452

The getSharedPreferences method appears to check for a .bak file to load the preferences from. This is why it says in the documentation that it will not work across multiple processes; to minimize I/O, it loads the prefs ONCE when you grab them and only backs them up when you close your application/activity

Which means that if I don't open/close my modules I'll still have the data from the bak file from when I opened it...

Community
  • 1
  • 1
Giom
  • 133
  • 10