The defaultValue is always being returned as 0, despite my attempt to return a different value when the pref key does not exist. I wonder why. Here's my piece of code -
public static final String PREFS_NAME = "MyPrefsFile";
public static final String PREFS_OLD_TRIM = "trimName";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
int trim_val = settings.getInt(PREFS_OLD_TRIM, 7);
I know for sure, in the initial run, that there is no pref key - PREFS_OLD_TRIM. So, i was expecting trim_val to get a value of 7. But it's getting 0.
Am i missing anything? Thanks. I am targeting API Level 8 device set.
To be on the safe side try changing PREFS_OLD_TRIM to random value at every run - this will make you sure that there is no such key in your preference file.
One thing for sure is, Preference will always return only the default value until you provide some value to it and commit(save). So here in this case you are trying to retrieve a value which is not present in the shared preference which obviously will return only the default value despite whatever value you might ask it to return.
Related
I'm using SharedPreferences to save multiple values from multiple Activities and Fragments and reuse them in various others. This works fine so far.
I mostly save Integers. Is it possible to set the default value of such a SharedPreference to be empty, so when the value is shown in a TextView, the TextView will be empty?
I want this for user convenience, so the user doesn't have to delete the default value in the field, if he wants to change it.
Here is an example of what I mean:
SharedPreferences sharedPref = getSharedPreferences("Datenspeicher", Context.MODE_PRIVATE);
int Stk_jahr = sharedPref.getInt("sp_stueckzahl", 0);
Stueckzahl.setText(String.valueOf(Stk_jahr));
In this example, if no value is saved in sp_stueckzahl, die TextView Stueckzahl will show a 0. I would prefer it to be empty.
Thank you
I want to create a int variable that doesn't loses its value after closing my app
with the use of internet.
Welcome to stack overflow.
Put your variable value in a database or put in shared preference in android. Then when you back on your app after closing just retrieve the value again and assign it to your variable.
Use shared preferences:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
then save like this:
prefs.edit().putInt("your_key", intValue).apply();
and read like this:
int value = prefs.getInt("your_key", defaultIntValue);
You can use shared preferences. Its quite easy and is under saving key values pair on the android documentation page here
public static final int variable_name =4;
Or if you want the value as changing each time of your request or any calculation
public/private static int variable_name=1;
String getString(String name, String defValue){...}
This is the definition of getString(...) method of SharedPreferences so I think it's possible if I run code below, it returns 1 two times:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
Timber.e(pref.getString("new", "1"));
Timber.e(pref.getString("new", "100"));
because at the first time its empty, so "1" will store, after that because of it has value ("1"), it will return it's value ("1") not default value ("100")
but it returns "1" and "100" and "new" does not store in my pref file (located in data/data/...)
Am I understanding it wrong or something goes wrong in this code?
Use can only get The data using getString.
to store data use Editor.commit();
Editor editor = settings.edit();
editor.putString("someKey", "someVal");
editor.commit();
only after that you can get this value.
String value = settings.getString("someKey", "someDefaultValueIfThisKeyNotUsedBefore");
In this example, you will recieve "someVal" if commit is used beforehand.
You must put"Something" to SharedPreferences.Editor, and commit them.
pref.getString wont store anything.
Refer to the links below:
https://developer.android.com/reference/android/content/SharedPreferences.html
https://developer.android.com/reference/android/content/SharedPreferences.Editor.html
I Am writing a code using SharedPreference to store username and password of a user but each time I entered information the older one in xml file are override by newer one what I have to to to get all my data?
SharedPreferences sp1=getSharedPreferences("myshared", 0);
sp1.edit().putString("name", name.getText().toString()).commit();
sp1.edit().putString("pass", pass.getText().toString()).commit();
sp1.edit().putString("age",age.getText().toString()).commit();
sp1.edit().putString("id",id.getText().toString()).commit();
It sounds like you're overwriting your shared preferences between activities. SharedPreferences are persistent like a file on disk, so you shouldn't ever have an issue with the values not being set, hence why you must be overwriting it.
You can get your SharedPreferences by doing
SharedPreferences sp1=getSharedPreferences("myshared", 0);
String name = sp1.getString("name", "noname");
String pass = sp1.getString("pass", "nopass");
...
You can determine if the name/pass was set by checking if they equal the default value (noname and nopass in this case, though it could easily be null).
I've got a number of preferences that I want to reset back to the defaults specified in my preferences xml file.
I do not want to reset all of my preferences - just a few select ones.
I've tried:
key=getResources().getString(R.string.myPref);
sharedPreferences.edit().remove(key).commit();
This clears the preference. However when my program then tries to pick the preference up
String myPref = sharedPreferences.getString(key, "");
It just returns the empty string.
How do I get the value from the XML file?
Thanks
Adding more complete code sample that I've been debugging:
//Get preferences
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
//Get preference key
key=getResources().getString(R.string.myPref);
//Get preference value
String myPref = sharedPreferences.getString(key, ""); // Returns a value that has been entered by a user
//Clear preference
sharedPreferences.edit().remove(key).commit();
//Reset preferences to default values - without overwritting all
PreferenceManager.setDefaultValues(currentContext, preferences, false);
//Get preference value again
String myPref = sharedPreferences.getString(key, ""); // Returns an empty string
Try PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
This is save as the last parameter ensures that user changed entries don't get overridden.
getDefaultSharedPreferences(Context).setDefaultValues(this, R.xml.preference, true);
Be sure to set last argument readAgain to true.
This will force to re-read the default values. If false, this method sets the default values only if this method has never been called in the past (or if the KEY_HAS_SET_DEFAULT_VALUES in the default value shared preferences file is false). To attempt to set the default values again bypassing this check, set readAgain to true.
I realise this question is kind of old, but hopefully this answer might help future viewers. It really helped me.
Quoting the answer:
Try to call the setter of the preference itself instead updating it on your own:
E.g. EditTextPreference.setText(). So the preference itself updates it's own value too. If you do the update on your own the preference will not fetch the new value because it doesn't even know that the persisted value has changed.
If you have a PreferenceFragment, you can get the preference with PreferenceFragment.findPreference().
If you have a PreferenceActivity, you can get the preference with PreferenceActivity.findPreference().
You call that with the preference key you assigned in your settings XML file and you get an instance of the corresponding preference. Then you cast it to a CheckBoxPreference, EditTextPreference, etc (the type you set in your XML file).
My personal adaptation:
Note: I was using this in a PreferenceFragment extended class, therefore the this.getActivity().
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
preferences.edit().remove(getResources().getString(R.string.pref_username)).apply();
EditTextPreference usernamePref = (EditTextPreference) findPreference(getString(R.string.pref_username));
usernamePref.setText("");
Hope it helps!