Android Shared Preferences (Java)

 Example : JAVA


// Storing data into SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("MySharedPref",MODE_PRIVATE);

// Creating an Editor object to edit(write to the file)
SharedPreferences.Editor myEdit = sharedPreferences.edit();

// Storing the key and its value as the data fetched from edittext
myEdit.putString("name", name.getText().toString());
myEdit.putInt("age", Integer.parseInt(age.getText().toString()));

// Once the changes have been made,
// we need to commit to apply those changes made,
// otherwise, it will throw an error
myEdit.commit();

String s1 = sharedPreferences .getString("name", "defaultvalue");
int a = sharedPreferences .getInt("age", 0);

Nested classes of Shared Preferences  

  1. SharedPreferences.Editor: Interface used to write(edit) data in the SP file. Once editing has been done, one must commit() or apply() the changes made to the file.
  2. SharedPreferences.OnSharedPreferenceChangeListener(): Called when a shared preference is changed, added, or removed. This may be called even if a preference is set to its existing value. This callback will be run on your main thread.
  3. contains(String key): This method is used to check whether the preferences contain a preference. 
     
  4. edit(): This method is used to create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object. 
     
  5. getAll(): This method is used to retrieve all values from the preferences. 
     
  6. getBoolean(String key, boolean defValue): This method is used to retrieve a boolean value from the preferences. 
     
  7. getFloat(String key, float defValue): This method is used to retrieve a float value from the preferences. 
     
  8. getInt(String key, int defValue): This method is used to retrieve an int value from the preferences. 
     
  9. getLong(String key, long defValue): This method is used to retrieve a long value from the preferences. 
     
  10. getString(String key, String defValue): This method is used to retrieve a String value from the preferences. 
     
  11. getStringSet(String key, Set defValues): This method is used to retrieve a set of String values from the preferences. 
     
  12. registerOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to registers a callback to be invoked when a change happens to a preference. 
     
  13. unregisterOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to unregisters a previous callback. 

Comments