Order of calls according to logcat is onCreate, setViewValues, setStrikethroughFlag, (ROTATE), onCreate, setViewValues:
SharedPreferences mSettings;
Editor spEditor;
#Override
public void onCreate(Bundle savedInstanceState) {
....
mSettings = getSharedPreferences("prefs", "")
spEditor = mSettings.edit();
setViewValues();
}
public void setViewValues() {
boolean isStrikeThru = mSettings.getBoolean(STRIKETHROUGH, false);
Log.d("TRACE", "setViewValues, strikethrough " + isStrikeThru);
}
public void setStrikethroughFlag() {
spEditor.putBoolean(STRIKETHROUGH, true);
spEditor.commit();
}
The logcat says setStrikethroughFlag() is called. Then I rotate the screen, onCreate and setViewValues are called. In setViewValues, I thought it would recognize the saved value of STRIKETHROUGH, true. But the logcat trace says the value of isStrikeThru is false.
Try calling the setViewValues() from the Constructor. In Screen orientation change, the oncreate of the activity will gets called again and resets your values.
From know i can see, that you creating local variable in your onCreate()
And in your setViewValues() you accessing your class field variable.
So i am not sure that you are calling getSharedPreferences() on your field variable.
The same is about your spEditor. Fix this and try one more time.
If this will not help you, give as the rest of your code.
UPDATE
Try this mSettings = getSharedPreferences("prefs", Context.MODE_PRIVATE);
The mistake was using quotes around the key when storing my shared preference. The keys didnt match so nothing was persisted, sorry.
Related
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 am making an application that contains a form and whenever a data clicks a button loads from a BD in a EditText, but every time I press a different button, the other EditText are cleared, I tried with:
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("data", myVariable);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
other = savedInstanceState.getString("data");
name.setText(other);
}
Sorry if I have not explained well, I need that every time they change Activity variables and I have not deleted. Any suggestions? Thank you!
Try using Android SharedPreferences instead. This is a persistent key-value storage that Android offers for its apps and was designed to covers issues like this. Here's the easy way to use it:
SharedPreference prefs = PreferenceManager.getDefaultSharedPreferences(this);
// To put a data (in this case a String from your EditText)..
Editor editor = prefs.edit();
editor.putString("data", yourStringHere);
editor.commit();
...
// ..and to retrieve it..
prefs.getString("data", null);
// NOTE: The 'null' in above method call could be replaced by any String you want;
// it basically specifies a default value to get when "data" is empty or doesn't
// yet exist.
Hope this helps.
I found all answers here and tried all solutions, still my shared prefs are not persistent.
Here's my code:
public static void setActivated(boolean activated) {
SharedPreferences sp = Utils.getContext().getSharedPreferences(
USER_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(ASD, activated);
editor.commit();
}
public static boolean isActivated() {
SharedPreferences sp = Utils.getContext().getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE);
return sp.getBoolean(ASD, true);
}
I've tried also:
editor.clear();
editor.put ..
editor.commit();
I've also tried with
editor.apply();
I even tried with both .apply() and .commit() and no luck.
Another idea was to try using a different mode for the files:
...getSharedPreferences(USER_PREFS, Context.MODE_MULTI_PROCESS);
The problem is that the values saved are not persistent. If I close the app and then re-open it the values are all wrong.
Does anyone have any ideas? I would also mention that the problem is only on some devices, for example HTC One S, Samsung Galaxy S3 (I tested on a different S3 and it worked perfectly).
EDIT: I call the save on a button click listener and I call isActivated when I load the fragment (after onViewCreated()).
Thanks!
Hi I think it should work. If clearing does not work, you could try the second option as detailed in my solution:
You have 2 options:
Get shared preference value during the life-cycle of the activity.
Call .clear before .commit
See my answer:
Android Persistent Checkable Menu in Custom Widget After Reboot Android
public abstract SharedPreferences.Editor clear()
Added in API level 1 Mark in the editor to remove all values from the
preferences. Once commit is called, the only remaining preferences
will be any that you have defined in this editor. Note that when
committing back to the preferences, the clear is done first,
regardless of whether you called clear before or after put methods on
this editor.
Returns Returns a reference to the same Editor object, so you can
chain put calls together.
In my user preferences class I was getting a null value on some other strings and my code was something like this:
SharedPreferences sp = Utils.getContext()
.getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if (session != null && !"".equals(session)) {
sessionId = session;
editor.putString(SESSION, sessionId).commit();
} else {
sessionId = null;
editor.clear().commit();
}
The editor.clear() was resetting all my other commits!
I don't know why, but it is working by just putting your prefs code inside the async task:
prefss = getSharedPreferences(ACCOUNT_PREFS_NAME, MODE_MULTI_PROCESS);
new AsyncSave(favNamesList).execute();
private static class AsyncSave extends AsyncTask<Void, Void, Boolean> {
String favNamesList;
AsyncSave(String favNamesList) {
this.favNamesList = favNamesList;
}
#Override
protected Boolean doInBackground(Void... params) {
prefss.edit().putString("favNamesList", strings).apply();
return null;
}
}
In Android 4, I have a preference value that I want to appear in the standard form E2C56DB5-DFFB-48D2-B060-D0F5A71096E0. But the user may enter the value without dashes. I would like to allow the user to enter it with any combination of whitespace or dashes, and simply have my code normalize it.
I am using the code below, and I see the log line, but it does nothing. I am guessing this is because Android has another Editor object open that overwrites my changes. Is there any other way to accomplish this?
public class UuidFragment extends PreferenceFragment {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
this.getPreferenceScreen().findPreference("pref_uuid").setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if (newValue.toString().length() != 0) {
String normalizedUuid=normalizeUuid(newValue.toString());
// TODO: this code runs but does nothing, I think because after committing the change, there is a higher level editor that commits the old value
// thereby undoing this change
if (!normalizedUuid.equals(newValue.toString())) {
Log.d(TAG, "Adjusting uuid from "+newValue.toString()+" to "+normalizedUuid);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(UuidFragment.this.getActivity());
SharedPreferences.Editor editor = settings.edit();
editor.putString(preference.getKey(), normalizedUuid);
editor.commit();
}
return true;
}
}
});
}
}
Try subclassing EditTextPreference and overriding setText(). In your setText() method, fix up the passed-in string before chaining to the superclass. Then, reference your EditTextPreference subclass from your preference XML.
I'ma a bit confused here. I'm trying to change the value of an EditTextPreference, but it is not updated in the view. (This is in a PreferenceActivity)
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.modify_instrument_preferences);
// Set default values
SharedPreferences customSharedPreference = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = customSharedPreference.edit();
modifying = getObjectWithName(); //Some object with a name;
editor.putString("namePref", modifying.getName());
editor.commit();
android.util.Log.d("TEST", "written: "+customSharedPreference.getString("namePref",""));
}
My printlns print out valid information, and the commit() returns true, but on clicking the EditTextPreference, it displays the old value. If I rotate the screen, causing the onCreate to get run again, the EditTextPreference has the right value.
So perplexing. Why isn't this change being updated in the UI?
Edit:
I'm not sure why the above isn't working, but I managed to change it just by doing:
EditTextPreference namePref = (EditTextPreference) findPreference("namePref");
namePref.setText("the text");
That updated the view everytime.
Although I know there are some constructs in place for PreferenceActivities to keep track of this info themselves, it doesn't seem to be well documented. I have found that adding an onPreferenceChangeListener to the preference will allow you to make those edits as soon as the preference is changed.