1

Well I have two apps.
First app owns the SharedPreferences, and the app saves some data to it by apply method.

And second app reads the preferences from the first app, (the first app saves preferences with MODE_WORLD_READABLE) and it configures itself with them.

It was like this.

There are a preference key "x". And the two apps were running at same time.
First app changed the value which is matched to "x"
And the second app didn't make any change.
After restarting second app, it does make change. Why is this problem happening?
Do I have to update SharedPreferences reference every time when I need to read some values from the first app?

ManDongI
  • 21
  • 4
  • Did you try with `commit()`? – Shaishav Aug 06 '16 at 09:46
  • refer http://stackoverflow.com/questions/5960678/whats-the-difference-between-commit-and-apply-in-shared-preference – sasikumar Aug 06 '16 at 09:47
  • commit does not working either – ManDongI Aug 06 '16 at 10:08
  • I think what you haven´t seen is, that the second app doesn´t know about the change or you are still holding an old reference from this sharedPreferences object. But this is only an assumption, you have to show some part of code, how do you read the preferences from the second app. – Opiatefuchs Aug 06 '16 at 10:14
  • @Opiatefuchs Yeah I realized that I was containing the old reference, so I changed the second app's code to call `getSharedPreferences` every time when it needs to get data, but it didn't work. Should I update the Context too? – ManDongI Aug 06 '16 at 11:55
  • I think so, update the context with `createPackageContext()` method. Sorry, I can´t give some further info, I never tried to get sharedPreferences from another app, no need until now. But maybe you have to put `android:sharedUserId`inside both manifests because it´s declared as following in the API: `Application with the same user ID can access each other's data` – Opiatefuchs Aug 06 '16 at 13:06

2 Answers2

0

SharedPreferences.apply() does the work in a thread (asynchronous), So it might take time. Hence after opening it the second time you could see the change. If you want immediate result use .commit() instead. But it will do the work in UI thread, and hence is not suggested

DarkCoderRises
  • 142
  • 2
  • 14
0

try using MODE_MULTI_PROCESS instead of MODE_WORLD_READABLE

MODE_MULTI_PROCESS: This method will check for modification of preferences even if the Shared Preference instance has already been loaded

Mr Schak
  • 21
  • 4