Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharedPreferences reads old values

I use SharedPreferences to write and later read values within different activities in my application. It used to work ok but lately it seems like it if wasn't sincronized. I mean, I write a value but then the other activity still reads the old value. Sometimes it works correcly. Any idea?

EDIT: This is a sample code:

First, from a thread:

SharedPreferences prefs = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("ComandToDo", value);
editor.commit();
... some code later:
alarmmanager.set(AlarmManager.RTC_WAKEUP, Miliseconds, sender);

In the alarm receiver:

SharedPreferences prefs = contexto.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
int value = prefs.getInt("ComandToDo", -1);    

And here comes the problem because "value" is not the value written in the thread.

like image 286
Ton Avatar asked Jan 02 '13 19:01

Ton


2 Answers

Here is what I encountered and what I did to fix it.

I was triggering an alarm from an Activity and in Broadcast-Receiver of that alarm I was updating Shared-Preferences which were read every time the app was launched.

After the alarm was triggered, whenever the app was launched it would get old values which were set from that activity only. No changes from Broadcast-Receiver were reflected.

The trick here is to set Shared-Preferences as MODE_MULTI_PROCESS

Generally we use MODE_PRIVATE, but do as follows:

SharedPreferences prefs = this.getSharedPreferences("Preferences", MODE_MULTI_PROCESS);

Note: After changing mode in code, it is advised to clear data of app to avoid issues while debugging.

EDIT: MODE_MULTI_PROCESS need min API 11

Before API 11 the workaround which I can think of is creating a database with 2 columns KEY & VALUE. This can be accessed from other modules.

like image 124
Kapil Jituri Avatar answered Oct 05 '22 01:10

Kapil Jituri


  1. SharedPreferences are documented not to work across processes, http://developer.android.com/reference/android/content/SharedPreferences.html, "Note: currently this class does not support use across multiple processes. This will be added later."

  2. This answer recommends encapsulation of data into a content provider, and the discussion also considers some other options, including shared SQLite: https://stackoverflow.com/a/5265556/1665128

  3. You also have plain old files in the file system. We used them in several projects, with locking, without any issues. May be an option for you as well.

like image 40
full.stack.ex Avatar answered Oct 05 '22 03:10

full.stack.ex