In Android, there are many different ways of storing data persistently such as SavedInstanceState, SQLite or Cloud Firestore for our applications. SharedPreferences is one of them that can store primitive data such as int, float, long, Boolean and String.
A SharedPreferences object points to a file that stores key-value pairs as shown in the below graphics. 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 out to know how to use SharedPreferences APIs to store and retrieve simple values. So, to access the 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 using the above editor object, see the below snippet.
editor.putInt("String_key", 123); //Integer editor.putFloat("String_key", 0.6f); //Float editor.putBoolean("String_key", true); //Boolean editor.putLong("String_key", 999); //Long editor.putString("String_key", "Name"); //String editor.putStringSet("String_key", myMap); //StringSet
Finally, commit or apply the changes.
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();
Here you have some differences between commit() and apply().
|commit() is synchronous.||apply() will asynchronously do disk I/O.|
|It is slower than apply().||It is much faster.|
|It returns true if the data stored successfully. Otherwise false.||It doesn’t return anything.|
Note: apply() will asynchronously do disk I/O while commit() is synchronous. So you really shouldn’t call commit() from the UI thread. In other word, apply() is faster as it is asynchronous. Above all commit() returns true if the save works, false otherwise.
Although in order to retrieve data from Shared Preferences we don’t need such SharedPreferences.Editor object instead 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);
While retrieving data we must have to pass a unique string key in any pref.get() method. For example, Lets’s say, you are retrieving Boolean type data, so that you should have to pass true or false as the default value.
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
➧ Delete a specific key/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.
Now you can learn to use this OnSharedPrefernceChangeListener interface. Must check out. That’s all for today, catch you in the next one.