Reset specific preferences Android - android

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!

Related

Android SharedPreferences check for empty or null

In my android application I am saving the last order did in Sharedpreference. When the user check for last order I am calling Sharedprefernce and showing it. That is working perfectly. But if nothing is saved in shared preference app is crashing. So I would like to check whther sharedpreference has any values saved or not first.
String lastOrder = sharedPreferences.getString("orderNO", "");
you just need to check isEmpty of you sharedPreference value before setting it
String lastOrder = sharedPreferences.getString("orderNO", "");
if (!lastOrder.equals("")){
orderField.setText(lastOrder);
}

How can I save data from an EditText component so it shows up when the app is reopened?

I am using Android Studio and programming in Kotlin. I haven't been able to find a way to save the data entered by the user so it appears when they reopen the app. Thank you ahead of time!
You have to store your data in shared preference when any click event listen or on edittext textwatcher you can set your character in preference but best way is on any click event save data on preference and when activity open set data from preference on edittext.
Store it in Shared Preferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
use this save the value..
Editor editor = sharedpreferences.edit();
editor.putString("key_name", "value"); //here give name and value to save
editor.commit();
use this to get the value.
String edittextvalue = pref.getString("key_name", null); //put edittextvalue where ever you what to show the value.
use this step to remove or clear the value
editor.remove("name");
editor.commit();

Is it possible to set the default value of an integer sharedpreference as an empty field?

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

how to use SharedPreference among activities

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).

Shared Preference problem in android app

in my app the first activity is a sign in page. In the edit boxes i am typing the user name and password. Those values are been move to an api and in return i am getting the userid from the server as an xml file.
I am parsing the xml file and storing the value in shared preferrence as follows
SharedPreferences.Editor IdEditor = Id.edit();
IdEditor.putString("useridValue", chap.getid());
IdEditor.commit();
And in the next time when the user opens the app i want to check whether it is already signed i or not. How to check this using the value stored in Shared preference
is your Id class extending SharedPreferences ?
maybe
String userId = Id.getString("useridValue");
If your preference is stored in the default preference then you can
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String userId = prefs.getString("useridValue");
on a side note you shouldn't really use a capital I on the IdEditor variable it should probably be idEditor
Check whether this entry already exist in shared preference, using:
id.containskey("useridvalue")

Categories

Resources