Shared Preferences in Android explained in detail

What is Shared Preferences?
Shared Preferences is one of the ways to store data persistently in Android application. Here the data is stored in Key-Value pair. It is simple and easy to implement compared to other data storage options like sqlite database where we need to write lot of codes.
In Shared Preferences the data is stored persistently, It means the stored data will remain even when the app is closed and removed from background. The data will be cleared if the app is uninstalled or if the user manually clears the app cache from settings.
The Shared Preferences is mostly used to store app settings like login / logout status, notification on / off etc.
We have three APIs to access preferences:
- getPreferences() : used from within your Activity, to access activity-specific preferences
- getSharedPreferences() : used from within your Activity (or other application Context), to access application-level preferences
- getDefaultSharedPreferences() : used on the PreferenceManager, to get the shared preferences that work in concert with Android’s overall preference framework
Before we go further, Lets also see the operating modes:
- MODE_PRIVATE: the default mode, where the created file can only be accessed by the calling application
- MODE_WORLD_READABLE: Any application can read the preference data. This may cause security holes in applications
- MODE_WORLD_WRITEABLE: Any application can edit the preference data. This may cause security holes in applications
- MODE_MULTI_PROCESS: This method will check for modification of preferences even if the Shared Preference instance has already been loaded
- MODE_APPEND: This will append the new preferences with the already existing preferences
- MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When it is set, it would enable write ahead logging by default
Initialising Shared Preferences
1 2 3 4 5 6 7 8 9 |
// Activity Context Context context = MainActivity.this; // or getActivity(); in case of Fragments SharedPreferences sharedPref = context.getSharedPreferences( "MyPrefs", Context.MODE_PRIVATE); // Here we are passing a unique name identifier for preference and mode applicable |
if we require activity-specific preferences, then no need of passing the identifier name as given below
1 2 3 4 5 |
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE); |
We can use SharedPreferences
to save any primitive data: booleans, floats, ints, longs, and strings.
Storing Data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE); // We need an editor object to make changes SharedPreferences.Editor edit = pref.edit(); // Store data. you may also use putFloat(), putInt(), putLong() as requirement edit.putString("name", "gadgetsaint"); edit.putBoolean("logged_in", true); // Commit the changes edit.commit(); |
We had to use the
commit()
method to commit our changes. There’s another method to do the same which isapply()
but that is asynchronous and won’t report failures.
Updating Data
Updating the Shared Preference is similar to storing data. Using Editor we will rewrite the same preferences key with a different value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE); // We need an editor object to make changes SharedPreferences.Editor edit = pref.edit(); // Store data. you may also use putFloat(), putInt(), putLong() as requirement edit.putString("name", "ASP"); edit.putBoolean("logged_in", false); // Commit the changes edit.commit(); |
Don’t forget to commit() or apply() the changes once done.
Reading Data
Retrieving values from Shared Preferences is done directly without using the Editor(). getBoolean()
, getFloat()
, getInt()
, getLong()
and getString() are used to fetch boolean, float, int, long and string values respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE); we will pass the key and default value in the second field String username = pref.getString("username", ""); boolean logged_in = String.valueOf(pref.getBoolean("logged_in", false); Log.d(TAG, username); Log.d(TAG, String.valueOf(logged_in)); //Output will be //ASP //false |
Deleting Data
Deleting preferences can be done by using remove().
1 2 3 4 5 6 7 8 9 10 11 12 13 |
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE); // Remove a particular key pref.remove("username"); // Commit changes pref.commit(); // this will delete the preference with key "username" |
To delete entire shared preferences stored in “MyPrefs” , we will use clear().
1 2 3 4 5 6 7 8 |
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE); // Delete all prefernces pref.clear(); |
Miscellaneous
To check if the shared preference exists or not:
1 2 3 4 5 |
boolean check = pref.contains("username"); |
Listening to changes in Shared Preferences:
1 2 3 4 5 6 7 8 9 10 11 12 |
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE); pref.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.d(TAG, "The key '" + key + "' is changed"); } }); |
Storing a String set in Shared Preferences:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE); // We need an editor object to make changes SharedPreferences.Editor edit = pref.edit(); // Store data HashSet<String> dataset = new HashSet<String>(); dataset.add("BMW"); dataset.add("Google"); dataset.add("Apple"); edit.putStringSet("brands", dataset); // Commit the changes edit.commit(); // Finally Retreive the dataset using getStringSet() method |
Please let me know of what you think about this blog post. Valuable suggestions and requests are always welcome. Help me improve this blog!
Follow GadgetSaint on Facebook / Twitter for updates.
Wanna start your blog or site in 5 mins? Check out Official WordPress recommended web hosting Bluehost.
how to delet data from string set
This is my code
SharedPreferences sharedPreferences = context.getSharedPreferences(“myPref”, Context.MODE_PRIVATE);
Set myStrings = sharedPreferences.getStringSet(“myStrings”,new HashSet());
SharedPreferences.Editor editor = sharedPreferences.edit();
myStrings.remove(val);
editor.commit();
it is removing from string set but not affecting to myPref file