Tuesday, 10 November 2015

Android SharedPrefences not being updated, cannot get the new value

I have another post for explaining how to " share data between two apps": (I recommend you to use the shared preference)


But you may find if you change shared preference from A app,  from B app can't get the new data, it still get the old one, it looks like the shared preference not being updated.

To solve this, you should do this in your B app:

getSharedPreferences(fileName, Context.MODE_PRIVATE);
getSharedPreferences(fileName, Context.MODE_MULTI_PROCESS);
As per document:
SharedPreferences loading flag: when set, the file on disk will be checked for modification even if the shared preferences instance is already loaded in this process. This behavior is sometimes desired in cases where the application has multiple processes, all writing to the same SharedPreferences file. Generally there are better forms of communication between processes, though.
This was the legacy (but undocumented) behavior in and before Gingerbread (Android 2.3) and this flag is implied when targeting such releases. For applications targeting SDK versions greater than Android 2.3(Gingerbread), this flag must be explicitly set if desired.
I knew there was a simple oversight in this.

No comments:

Post a comment