I use this function to extract shared preferences from Android App. However, I am not sure if the requested field exists. Should I wrap the code inside try catch or getString() is safe when the field does not exist?
public String loadPreferences(String what){
SharedPreferences settings =this.getSharedPreferences("settings", Context.MODE_PRIVATE);
String content =settings.getString(what, "empty");
return content;
}
If by "field", you mean the value keyed by whatever what is, getString() will not return null in your code snippet. It will return the value keyed by whatever what is, or "empty" if there is no value for that preference.
You should read documentation of getString here, it clearly says,
Returns the preference value if it exists, or defValue. Throws
ClassCastException if there is a preference with this name that is not
a String. This value may be null.
In your case, defValue is "empty"
So exception is possible only when value you are trying to return is not of specified type, it should never be the case of getString() though
If you search through this link : https://developer.android.com/reference/android/content/SharedPreferences.html
You will find this method :
getString(String key, String defValue)
Which means if you havnt stored anything in SharedPreferences with this key and you are trying to get value for this key than it will return default value
So in your case
String content =settings.getString(what, "empty");
For what key if you havnt stored anything with this key and if you are trying to get its value than it will return default value that is "empty" in your case
Related
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);
}
In my onCreate() I have:
if(sharedPref.getString("name",null)==""){EditText.setText("Something");}
else{EditText.setText(sharedPref.getString("name",null));}
And then in my onStop() I have:
sharedPrefEditor.putString("name",EditText.getText().toString());
The EditText shows only the hint when I first install and run it. It does seems to display the correct text when it's started later, however.
Don't use == to compare content of Strings. Use equals() instead :
if(sharedPref.getString("name",null).equals("")){
EditText.setText("Something");
}
Why should I use equals instead of ==
First of all you are not using correctly the shared preferences. You are typing null as second parameter which is the value you will get if the key you typed as first parameter is not defined. This is not a problem itself but then in your if sentence you are comparing it to an empty string.
So first of all use equals instead of ==and then if you want to receive an empty string if the key is not defined type an empty string as second parameter of SharedPreferences.gerString method.
Hope it helps ;)
If "Something" is to be used if preference not set, then:
EditText.setText(sharedPref.getString("name","Something"));
getString() will automatically return "Something" if preference is not set. No need of extra code.
String strName = sharedPref.getString("name","");
if(!strName.isEmpty()){
EditText.setText(strName);
}else{
EditText.setText("Something");
}
The operator == can not be used to compare strings in Java.
if(string1.equals(string2){
}
Also, you set a value to SharedPreferences, but you never commit the changes.
sharedPrefEditor.commit();
OnCreate
String prefsVal = sharedPref.getString("name", null);
if(prefsVal.equals(null)){ //If default value was returned
EditText.setText("Something");
}else{
EditText.setText(prefsVal);
}
OR
The following will turn your posted code into a single line solution. The second parameter passed to SharedPref is the default value to be returned if no vale was found for the given key.
EditText.setText(sharedPref.getString("name", "Something");
OnStop
sharedPrefEditor.putString("name", EditText.getText().toString());
sharedPrefEditoy.commit();
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!
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.
I am working on android. i want to know that whether this is possible to check that
following key,value pair has created or not ?
String filename=getIntent().getExtras().getString("FILE_NAME");
textView_file_name=(TextView)findViewById(R.id.TextView_fileName);
textView_file_name.setText(filename);
before my first programing statement, means before getting the value of FILE_NAME, i want to check whether this key-value pair has build or not ? because i am getting null pointer exception in the case if it is not done before these statement. So i want to know that is any code so i can check intent.putExtras().getString("FILE_NAME"); has done or not.
You can store in a String variable if you send String data as below and print in cosole to check it:
Bundle b=intent.getExtras();
String str=b.getString("FILE_NAME"); //IF YOU HAVE STRING AS VALUE THEN USE getString() else use accordingly.
System.out.println(str);