I'm creating Shared Preferences as follows
preferences = getSharedPreferences("text", 0);
final Editor editor = preferences.edit();
String s1 = serverIP.getText().toString();
String s2 = serverPort.getText().toString();
String s3 = syncPass.getText().toString();
String s4 = proxyServer.getText().toString();
String s5 = proxyPort.getText().toString();
editor.putString("SERVERIP", s1);
editor.putString("SERVERPORT", s2);
editor.putString("SYNCPASS", s3);
editor.putString("PROXYSERVER", s3);
editor.putString("PROXYPORT", s3);
and onCreate I want to display the values in a new set of TextViews, but the first time I don't have any values stored in the shared preferences and will get a NULL Pointer exception.
I want to know if there is any built-in method which can check if the SharedPreferences contains any value or not, so that I can check if the key exists and if not, then replace the new set of TextViews with the preferences value.
getSharedPreferences("myPrefs", MODE_WORLD_READABLE); String username = myPrefs. getString("USERNAME",null); String password = myPrefs. getString("PASSWORD",null); if username and password are present, they will have a value otherwise they will be null.
To check if a key or record is present in shared preferences we have to use containsKey() method. This methods takes key as value and checks if the key is present in sharedpreferences. If the key is present it will return true else it will return false.
getBoolean(String key, boolean defValue): This method is used to retrieve a boolean value from the preferences. getFloat(String key, float defValue): This method is used to retrieve a float value from the preferences. getInt(String key, int defValue): This method is used to retrieve an int value from the preferences.
Try contains(String key)
Accorting to the Javadocs,
Checks whether the preferences contains a preference. Returns true if the preference exists in the preferences, otherwise false.
Every method for fetching values from SharedPreferences
has default value which is returned in case the key does not exist
preferences = getSharedPreferences("text", 0);
String value = preferences.getString("unknown_key",null);
if (value == null) {
// the key does not exist
} else {
// handle the value
}
Try out
SharedPreferences shf = getSharedPreferences("NAME_SharedPref", MODE_WORLD_READABLE);
String strPref = shf.getString("SERVERIP", null);
if(strPref != null) {
// do some thing
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With