Reputation: 2062
I'm storing user's profile picture uri in SharedPreferences. When the user updates their profile image, it should get updated in SharedPreferences as well. However, when I try to retrieve the new image uri, I always get the old uri, but if I turn the device off or force the app to stop, the value is updated. I've noticed that this problem happens on android 6.0 and 8.0, tried kitkat and it works fine. I found some solutions on the internet that suggested using apply() instead of commit(),but neither worked.
Here's the code I use to save the image uri:
SharedPreferences login = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = login.edit();
editor.putString( USER_PROFILE_PIC, selectedImage.toString());
editor.apply();
And here's how I retrieve the image uri:
SharedPreferences login = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = login.edit();
String profileImageURI = login.getString( USER_PROFILE_PIC, "" );
Update
The value is returned correctly in the activity where I update the SharedPreferences. However, in the syncAdapter, when I retrieve the value from SharePreferences, it returns the old value.
Upvotes: 0
Views: 172
Reputation: 2062
Finally figured it out, according to this answer, in Android < 2.3
, one process can make changes, and the other one can read the changes. After Android > 2.3
, this was still possible, but need to set MODE_MULTI_PROCESS
when using SharePreferences
, so the code becomes like this:
SharedPreferences prefs = context.getSharedPreferences(context.getPackageName() + "_preferences", Context.MODE_PRIVATE| Context.MODE_MULTI_PROCESS); // context.getPackageName() + "_preferences" is the name of the sharePreferences file
And the I first found solution in this blog
Upvotes: 0