I\'m trying to use SharedPreferences to save settings. But I can\'t seem to get the data to be shared between any of my activities. The code I\'m using does manage to save s
As was said, use getSharedPreferences(String name, int mode)
rather than getPreferences (int mode)
. Specifically, if you are interested, the documentation for these two methods illustrates the difference. According to the Android documentation getPreferences(int)
does the following:
Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.
You are using getPreferences(MODE). Use getSharedPreferences("PREF_NAME", MODE) instead. This way you will provide a name to particular preference and then you can call it by its name (PREF_NAME here) from whatever the activity you want.
//------get sharedPreferences
SharedPreferences pref = context.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
//-------get a value from them
pref.getString("NAME", "Android");
//--------modify the value
pref.edit().putString("NAME", "Simone").commit();
//--------reset preferences
pref.edit().clear().commit();
You should use this
SharedPreferences pref = context.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
Or
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
If you aren't doing anything fancy with preferences I would just use the default way of accessing them. It seems to be your problem.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Here is a great write with more detail, put you are doing everything pretty much correctly except for the getting your handle. How do I get the SharedPreferences from a PreferenceActivity in Android?
ALSO: Don't forget the new way is to call .apply() instead of .commit() This was in one on the #io2012 videos..
If you had the same problem as me, it's very simple. When you to go save the preferences, save it like this:
SharedPreferences sp = getSharedPrefenreces("Preference",MODE_PRIVATE);
And not:
SharedPreferences sp = getSharedPrefenreces("Preference's name",Context.MODE_PRIVATE);
I know how so much is important the SharedPrefenrences in some cases.