I'm using SharedPreferences to store the value of multiple checkboxes and some strings, and it's doing well. When I try to use it to store the value of a switch it doesn't work, and keep getting the default value.
I initialize like this
SharedPreferences.Editor editor;
SharedPreferences prefs;
I put this on "onCreate"
editor = getSharedPreferences(FirstStart.MY_PREFS_NAME, MODE_PRIVATE).edit();
prefs = getSharedPreferences(FirstStart.MY_PREFS_NAME, MODE_PRIVATE);
And then I'm testing it on the "onClick" event of the switch (I'm using toasts to test)
public void clickSwitchAlarm(View view) {
editor.putBoolean("swAlarma", swAlarm.isChecked());
Toast.makeText(MainMenu.this, "isChecked() value: " + swAlarm.isChecked(), Toast.LENGTH_SHORT).show();
//Toast.makeText(MainMenu.this, "getBoolean value: " + prefs.getBoolean("swAlarma", false), Toast.LENGTH_SHORT).show();
}
When I check the "isChecked()" value it works fine, but when I check the SharedPreferences stored value it shows the default.
Does anybody know what's happening here? Thank you!
(Working with API15)
After putting the value inside the editor, you must confirm the operation by calling commit() or apply() method`s :
editor.commit();
//or
editor.apply();
Otherwise your operation will not be validated and the value will not be saved.
Related
I have a Sharedpreferences to check if the user has activated the pro section with InAppPurchase and I check it every time Mainactivity is opens, like this:
SharedPreferences s = c.getSharedPreferences("app" , MODE_PRIVATE);
String value = s.getString(key , " ");
Log.i("myapp" , value);
and if some one tries to change the value manually my app warns him .so I tried to test my app's security and changed the value manually with text editor from data/data/com.myapp.package/shared_prefs/ let's say the value was 39m49ur3.I changed it a to 87mjr83.Then I started the app and the value from the logs stil was 39m49ur3 . I closed the app and started it again but no change was seen except when I clear the RAM of my device then start the app , finally then the value I got from the logs is what really is in the shared_prefs folder.
What can I do about this?
Save like this,
SharedPreferences pref = c.getSharedPreferences("app", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("myapp", "string value");
editor.commit();
Get Like this,
pref.getString("myapp", null);
//to save String in shared preferences
public void put(String key, String value) {
mSharedPreferences.edit().putString(key, value).apply();
}
//to get value from shared preferences
public String get(String key, String defaultValue) {
return mSharedPreferences.getString(key, defaultValue);
}
Try to use
editor.apply();
Instead of
editor.commit();
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures.
In my app I was using for more than 1 year "Shared preferences" to store some boolean values (if the user has seen the intro page for example). Now I added one more setting (if the user has seen the help page!) and all the settings stopped working...
I tried changing "commit" to "apply" with no luck. How could by just adding one more shared preference to make it stop working? Is there any properties limit?
My code:
public SharedPreferences getSettings() {
SharedPreferences settings = getSharedPreferences(AppConstants.PREFS_NAME, 0);
return settings;
}
old Activity for Intro:
private void saveUserHasSeenIntro() {
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS, true);
editor.commit();
}
where intro boolean is being read:
Boolean hasShownIntroSteps = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS, false);
if ( !hasShownIntroSteps ) {
// show intro
} else {
New activity for help:
private void saveUserHasSeenHelp() {
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, true);
editor.commit();
}
where the "help" boolean is read:
Boolean hasSeenHelp = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, false);
if ( !hasSeenHelp ) {
// show help activity
} else {
Your methods are fine and they should work perfectly. Check a couple of things just in case:
Ensure you don't call clear() or remove() method of the SharedPreferences editor after saving your prefs by mistake.
Ensure the constants AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS and AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS have different values as the former could overlap the second by mistake.
Just add a breakpoint after setting the new pref and read the value to check if it's set just after it.
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, true);
editor.commit();
Boolean hasSeenHelp = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, false);
In some extreme cases you could even implement SharedPreferences.OnSharedPreferenceChangeListener to see where your SharedPreferences are being changed to avoid unwanted pref sets.
It can be a Memory Limitation on your SharedPreferences file and usually this comes with an OutOfMemoryException. I guess if something like that would happen you would probably seen it in your code, unless you are not reading/writing in another Thread. How big is your SharedPreferences file in numbers of key - value pair ?
I have in my main activity access to a shared preference like this:
preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("maxValue", "666");
Boolean test = editor.commit();
when I open my Preference activity I see for that preference the value 666. So that works without issue.
Now I want to do pretty much the same in my Preferences.java, background is that I want to check the input string and notify the user if something is wrong, e.g. I want to make sure that if the users sets the maxValue above 1000, to tell him that this is too high and set it to 899 automatically. I have implemented a change listener:
#Override
public boolean onPreferenceChange(Preference pref, Object newValue)
{
if(Integer.valueOf(etAdd.getEditText().getText().toString()) > 899)
{
SharedPreferences.Editor editor = preferences.edit();
editor.putString("maxValue", "899");
Boolean test = editor.commit(); //test shows true
Toast.makeText(Preferences.this, "value too high have set it to the maximum of 899", Toast.LENGTH_LONG).show(); //this toast is shown
}
return true;
}
When I re-open this preference, even after leaving the preference activity and returning back to it, I see the value the user has entered, e.g. 1000.
anyone an idea?
thanks.
According to the documentation onPreferenceChange is called BEFORE the changes are written. If you return true (accept new Value), after leaving onPreferenceChange the newValue object is successfully applied and your modifications are ignored. That is the reason of mentioned behavior. Returning false would do the trick.
To project your corrected value to PreferenceActivity immediately, use SetText on your EditTextPreference.
Using typecasted newValue.toString() instead of using contents of the corresponding EditText is also worth considering.
In my application I want to clear SharedPreferences on button click. This is what I'm using for storing values in it:
SharedPreferences clearNotificationSP = getSharedPreferences("notification_prefs", 0);
SharedPreferences.Editor Notificationeditor = clearNotificationSP.edit();
Notificationeditor.putString("notificationCount", notificationCountValue);
Notificationeditor.commit();
And the following code on onClick():
SharedPreferences clearedNotificationSP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editorSP = clearedNotificationSP.edit();
editorSP.remove("notificationCount");
editorSP.commit();
System.out.println("Saved in SP clearedNotification: "+ clearNotification);
I was printing the value after clearing it but still I was getting the same value.
What am I missing?
Any kind of help will be appreciated.
getDefaultSharedPreferences and getSharedPreferences("notification_prefs", );
returns two different SharedPreferences. Since you are adding notificationCount inside notification_prefs, you should retrieve SharedPreference with getSharedPreferences("notification_prefs", );
getDefaultSharedPreferences uses a default preference-file name, while getSharedPreferences use the filename you provided as paramter
How to remove some key/value pair from SharedPreferences ? I have put and I to remove that from prefs.
SharedPreferences mySPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = mySPrefs.edit();
editor.remove(key);
editor.apply();
Here editor is the sharedPreferences editor.
It is important to note that, unless you're planning on doing something with the return value of the commit() call, there is absolutely no reason for using the synchronous commit() call instead of the asynchronous apply() call.
Keep in mind that if you're calling this from the main/UI thread, the UI is blocked until the commit() has completed. This can take upwards of around 100ms as apposed to about 5ms for the apply. That may not seem like much, but if done continually throughout an application, it will certainly add up.
So, unless you're planning on doing something like this, hopefully on a separate thread:
editor.remove(String key);
boolean success = editor.commit();
if (!success) {
// do something
}
You should instead be doing this:
editor.remove(String key);
editor.apply();
It's very simple:
private SharedPreferences sharedPreferences() {
return PreferenceManager.getDefaultSharedPreferences(mContext);
}
public void clearSharedPreferences() {
sharedPreferences()
.edit()
.remove(SOME_KEY_1)
.remove(SOME_KEY_2)
.remove(SOME_KEY_3)
.apply();
}
SharedPreferences.Editor.remove(key)
commit();
Here is how I tacked this issue.
First I created an instance of SharedPreference as
SharedPreferences mobilePreference;
then I used this sharedPreference as
mobilePreference = this.getSharedPreferences("in.bhartisoftwares.amit.allamitappsthree", Context.MODE_PRIVATE);
Here "in.bhartisoftwares.amit.allamitappsthree" is my package name and I am using Context.MODE_PRIVATE, because I want to manipulate this shared preference only for this package name.
Then I am deleting the selected sharedPreference (key of my sharedPreference is mobileString) as follows:
mobilePreference.edit().remove("mobileString").commit();
See the code as full below:
SharedPreferences mobilePreference = this.getSharedPreferences("in.bhartisoftwares.amit.allamitappsthree", Context.MODE_PRIVATE);
mobilePreference.edit().remove("mobileString").commit();
Information
Just check sharedpref class is extended to Map that's why there is remove method
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.remove(String key);
editor.apply();
Here editor is the sharedPreferences editor.