SimpleSharedPreferences on GitHub


 Shared preferences are used to save values permanently within the app. It is saved in an XML file using Key-Value pair.

SharedPreferences provide API's to read and write these Key-Value pairs.

mContext = getApplicationContext();
// mContext = getActivity().getApplicationContext(); // In Fragment
SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(mContext)
SharedPreferences.Editor mEditor = mPreferences.edit();

mEditor.putString("STRING_KEY", "STRING_VALUE"); // mEditor
mEditor.commit(); // mEditor
...
...
...
mEditor.putInt("INTEGER_KEY", 50); // mEditor
mEditor.commit(); // mEditor
...
mPreferences.getString("STRING_KEY", "STRING_DEF_VALUE");  // mPreferences
...

To put a Value an Editor has to be created. After Putting the values, editor has to be committed.
Editor Object is used to put values & SharedPreferences Object is used to get Values.

  This is quite confusing.


If an key is wrongly used to fetch values then ClassCastException is thrown.

Let try SimpleSharedPreferences to do the same.

SimpleSharedPreferences mPreferences = new SimpleSharedPreferences(mContext);
mPreferences.putString("STRING_KEY", "STRING_VALUE");  // Put String
mPreferences.putInt("INTEGER_KEY", 50);  // Put Int
mPreferences.getString("STRING_KEY", "STRING_DEF_VALUE"); // Get String

No need to create multiple Objects.

If an key is wrongly used to fetch values then ClassCastException is thrown. Clearly stating the type.

mPreferences.getString("INTEGER_KEY", "STRING_DEF_VALUE"); // Get String with Integer Key

Error:
==========================================================
ClassCastException : INTEGER_KEY's value is not a string
==========================================================


Other APIs in SimpleSharedPreferences

public boolean incrementAppOpenedCount() // Increment's App opened count

public int getAppOpenedCount() // Get the number of times app opened

public boolean isLogEnabled() // Log Status

public void setLogEnabled(boolean enableLog)// default false

Refer SimpleSharedPreferencesDemo for all the available API's

In this, putStringSet / getStringSet is back ported to API-1 & hence can be used pre API level 11

All APIs are available as in `SharedPreferences` and `SharedPreferences.Editor` including registerOnSharedPreferenceChangeListener & unregisterOnSharedPreferenceChangeListener

No Edit, No Commit, Only Put & Get.

 

SimpleSharedPreferences on GitHub


Download Sample APK.

Refer Sample