In Android, there are many different ways of storing data persistently such as SavedInstanceState, SQLite or Cloud Firestore for our applications. And Shared Preferences is one of them to store primitive data such as int, float, long, Boolean and String.
In Shared Preferences the data is stored in key-value pair as shown in the below graphics. Also remember, Shared Preference is a persistent database, it means the stored data will be remaining as it is even when the app is closed and removed from the background. But the data will be cleaned only if the app is uninstalled or if the user manually clears the app cache from settings.
However, this article will help you to know how to use SharedPreferences APIs to store and retrieve simple values. So, to access Shared Preferences file we have to call anyone from these below “get” methods.
- getPreferences(): Use this from an Activity if you need to use only one shared preference file for the activity.
- getSharedPreferences(): Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any Context in your app.
- getDefaultSharedPreferences(): used to get the shared preferences that work with Android’s overall preference framework. And for that, we need to use PreferenceManager.
Let’s also talk about some of the available operating modes that can be used to share or secure our Preference file.
- 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
- MODE_MULTI_PROCESS – This method will check for modification of preferences even if the SharedPreferences instance has already been loaded
- MODE_PRIVATE – By setting this mode, the file can only be accessed using calling application
- MODE_WORLD_READABLE – This mode allows other application to read the preferences
- MODE_WORLD_WRITEABLE – This mode allows other application to write the preferences
As we have discussed earlier, there is a total of three “get” methods to access Share Preferences or to create a Shared Preferences object. Let’s discuss those one by one.
➧ How to use getPreferences()
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
As shown in the above line, we have a SharedPrefrences object called pref using getPreferences() which requires to pass an operating mode such as Context.MODE_PRIVATE.
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_file_name), Context.MODE_PRIVATE);
We can also call getSharedPreferences to access Shared Preferences API where we have to pass a preference file name (Unique String) and an operating mode (int). When naming your shared preference files, you should use a name that’s uniquely identifiable to your app. An easy way to do this is prefix the file name with your package name or application ID. For example: “com.dailycoding.sharedpreferences.PREFERENCE_FILE_KEY”.
Also, define your key in the String.xml file like below snippet.
<string name="pref_file_name">com.dailycoding.sharedpreferences.PREFERENCE_FILE_KEY </string>
Remember, If you are writing Shared Preferences code in separate java file then to access the API you should have to call like, context.getPreferences or context.getSharedPreferences where the context needs to be passed from your activity or fragment.
SharedPreferences pref = context.getPreferences(Context.MODE_PRIVATE); // OR SharedPreferences pref = context.getSharedPreferences(getString(R.string.pref_file_name), Context.MODE_PRIVATE);
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
This is another way to access the SharedPreferences API to save app settings. Typically getDefaultSharedPreferences() used to get the default shared preference file for our entire app. And for that we must use PreferenceManager.
As the above snippet shows SharedPreferences instance called pref that points to the default file that is used by the preference framework in the given context.
In order to save or modify data in Shared Preferences, we need a SharedPreferences.Editor (an interface). See this below line.
SharedPreferences.Editor editor = pref.edit();
Let’s save data by the editor object, see the below snippet.
editor.putInt("String_key", 123); editor.putFloat("String_key", 0.6f); editor.putBoolean("String_key", true); editor.putLong("String_key", 999); editor.putString("String_key", "Name"); editor.putStringSet("String_key", myMap);
Finally commit or apply the change.
editor.apply(); //OR editor.commit();
Let’s combine all the steps for saving data in Shared Preferences.
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_file_name), Context.MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putInt("String_key", 123); editor.putFloat("String_key", 0.6f); editor.putBoolean("String_key", true); editor.putLong("String_key", 999); editor.putString("String_key", "Name"); editor.putStringSet("String_key", myMap); editor.apply();
Although to retrieve data from Shared Preferences we don’t need such SharedPreferences.Editor object. So we can call these below available methods directly with SharedPreferences instance called pref.
pref.getInt("string_key", -1); pref.getFloat("string_key", 0.0f); pref.getBoolean("string_key", false); pref.getLong("string_key", 0); pref.getString("string_key", ""); pref.getStringSet("string_key", null);
Whatever the pref.get..() method is, while retrieving data we must have to pass a unique string key and a correspond default value. For example, if you are retrieving Boolean type data you should pass true or false as the default value.
Removing or Clearing Data
Sometimes we need to remove a specific data or even we need clean up the whole SharedPreferences. In such case we can follow the below snippet
➧ Remove a specific data
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_file_name), Context.MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.remove("string_key"); editor.apply();
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_file_name), Context.MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.clear(); editor.apply();
Remember: whenever you are adding or removing data in SharedPreferences, that means you are actually modifying in the Shared Preferences object. In such cases, you should have to commit or apply the change at the end.
I hope now you can implement SharedPreference in your Android applications. For more guidance on this topic please check out these below tutorials.
Next, we will be discussing on another important topic OnSharedPrefernceChangeListener. So that’s all for today, catch you in the next one.