Android SharedPreferences check for empty or null - android

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);
}

Related

How Do I Set The Value Of A String In Android?

I have a string and a button as follows:
String message = "Hello World"
button.OnClickListener(......){
message = "123456789";
}
So here is what I want,
When the app starts the string is "Hello World" but when the user clicks the button it changes to "123456789" and I want the string to change permanently for lifetime.
So when the user restarts the application or reinstall it the string is still
"123456789".I think this comes under Shared Preferences.
Please Help,I really need this
You can save that string in Shared Preferences, and get it all the from there. If is no value, you can get default value from resources or you can provide your own default String. Note that you can do that for lifetime. If user delete the app or clear cache, your view will display default value, Hello World.
Edit
You can use android:allowBackup="true" from manifest in order to keep old Shared Preference values.
There is a chance data from SharedPreferences is gone when you reinstall especially if you uninstall the app first, same case as local database using SQLite. You can try using database from your local server.
To save a String in SharedPreferences :
SharedPreferences.Editor editor = getSharedPreferences("com.package.name", Context.MODE_PRIVATE).edit();
editor.putString("keyName", message);
editor.apply();
To get it back :
SharedPreferences sharedPrefs = getSharedPreferences("com.package.name", Context.MODE_PRIVATE);
message = sharedPrefs.getString("keyName",defaultValue);
When the user modifies it, save it. When the app start, get it with as default value "Hello World" so that while the user hadn't click the button, it will stay as Hello World.
For Restarting Shared Preference is the best mechanism but for reinstall allowbackup works on API level 23 and above,
you can consider to update the value on server once you update in your Shared Preferences for the first time and during reinstall can do a API call check for the same for the particular user.

Retrieving SharedPreferences

I'm working with an android application, and when my application is open I want to log in. I'm using shared preferences for saving data.
How can I control three cases: if his credentials are null, if that user exists and does not have to register and save his credentials again and also if username and password he entered is correct and is the same with them he used when entered for the first time.
Use this code to retrieve values from sharedPreferences.
SharedPreferences sharedPref ;
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
int status=sharedPref.getInt("status",0);
if(status==1){
//do something here you want to do
}else if(status==2){
//do something here you want to do
}
Read the documentation here http://developer.android.com/reference/android/content/SharedPreferences.html
Also check this http://www.tutorialspoint.com/android/android_shared_preferences.htm

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

Reset specific preferences 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!

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