
In this article, you will learn how to use Shared Preferences API in Android with the help of examples.
What is Shared Preferences in Android?
SharedPreferences API helps us to store a small amount of data in a file. The data here is a primitive data type (like integer, string, etc.). For example: In a gaming app, you have to save the level that has been finished so that when the user opens the app later, you can resume the game from the last level.
How does Android Shared Preferences Work?
We store primitive data types like integer, string, boolean, etc. in shared preferences. We save them in the form of key-value pairs. The value is the actual data and the key helps us to identify it. We use the key whenever we want to get the value. Let’s understand it with examples.
First, we have to open the SharedPreference file. We can do it with the help of getSharedPreferences() method from the Context class.
public abstract SharedPreferences getSharedPreferences (String name, int mode)
name – the name of the file. While naming the file, choose a name that is uniquely identifiable to your app. An easy way to do this is to use the application ID. Example: “com.example.helloworld.USER_INFO”
mode – It is the operating mode. For security reasons, we use MODE_PRIVATE.
The method returns the SharedPreferences object. It helps us to read and write values to the file.
private fun createSharedPrefFile(context: Context) {
val sharedPrefFile = context.getSharedPreferences(
"com.example.helloworld.USER_INFO",
Context.MODE_PRIVATE
)
}
Call this method from the onCreate() of Activity class.
createSharedPrefFile(this.applicationContext)
Now, let’s see how to read and write values to the file.
Writing Data to SharedPreferences File:
To write data, call edit() method. It returns an Editor object. It provides methods like putInt() to store the data. And to save changes, call apply() or commit().
Let’s store the user’s finished game level.
val sharedPrefFile = context.getSharedPreferences(
"com.example.helloworld.USER_INFO",
Context.MODE_PRIVATE
)
val editor = sharedPrefFile.edit()
editor.putInt("COMPLETED_LEVEL", 10) // write values
editor.apply() // save changes
In the above example, COMPLETED_LEVEL is the key and 2 is the value. We use this key whenever we want to get the value.
Difference between apply() and commit():
Editor class provides apply() and commit() methods to save changes. The apply() method saves the values immediately on a background thread. It is an asynchronous process.
The commit() saves the data synchronously. So, you should avoid calling it on the main thread.
Reading Data From SharedPreference File:
Let’s read the game level that we have saved above. To read values, we can call methods like getInt().
public abstract int getInt (String key, int defValue)
key – It is the key we used while saving the data.
defValue – It is the default value. If the key is not found in the file, this value will be returned.
val sharedPrefFile = context.getSharedPreferences(
"com.example.helloworld.USER_INFO",
Context.MODE_PRIVATE
)
val gameLevel = sharedPrefFile.getInt("COMPLETED_LEVEL", 1)
In the above example, we have passed COMPLETED_LEVEL and 1 to the getInt() method. COMPLETED_LEVEL is the key we used while saving the data and 1 is the default value. If the key is not present in the file, 1 will be returned.
For other primitive data types, we can use the following methods:
- putBoolean() and getBoolean() – for boolean values
- putFloat() and getFloat() – for float values
- putLong() and getLong() – for long values
- putString() and getString() – for string values
- putStringSet() and getStringSet() – for a set of String values
How to Store Double Values in SharedPreferences File?
Editor class has no putDouble() and getDouble() methods. To store a double value, we can convert it to a string and call the putString() method. But, it is not a recommended method because we end up wasting bits. The most efficient way is to convert the double to its equivalent raw long bits and store the long value.
Saving Double Value:
val sharedPrefFile = context.getSharedPreferences(
"com.example.helloworld.USER_INFO",
Context.MODE_PRIVATE
)
val editor = sharedPrefFile.edit()
editor.putLong("SOME_DOUBLE_VALUE", java.lang.Double.doubleToRawLongBits(10.2))
editor.apply()
Reading Double Value:
val sharedPrefFile = context.getSharedPreferences(
"com.example.helloworld.USER_INFO",
Context.MODE_PRIVATE
)
// get the saved long value
val longValue =
sharedPrefFile.getLong("SOME_DOUBLE_VALUE", java.lang.Double.doubleToLongBits(0.0))
// convert the long back to double
val doubleValue =
java.lang.Double.longBitsToDouble(longValue)
How to Store Multiple Values in SharedPreferences?
To store multiple values, call corresponding put methods. At the end, call commit() or apply() to save changes.
val sharedPrefFile = context.getSharedPreferences(
"com.example.helloworld.USER_INFO",
Context.MODE_PRIVATE
)
val editor = sharedPrefFile.edit()
editor.putInt("COMPLETED_LEVEL", 10) // store game level
editor.putString("USER_NAME", "John") // store user's name
editor.putString("USER_COUNTRY", "Canada") // store user's country
editor.apply() // save changes
How to Delete Data from the Shared Preferences File?
There are two methods to remove data from the preference file – remove() and clear().
remove():
public abstract SharedPreferences.Editor remove (String key)
It takes the key and deletes the corresponding value.
val sharedPrefFile = context.getSharedPreferences(
"com.example.helloworld.USER_INFO",
Context.MODE_PRIVATE
)
val editor = sharedPrefFile.edit()
editor.remove("COMPLETED_LEVEL")
editor.apply()
clear():
public abstract SharedPreferences.Editor clear()
It removes all the values from the preference file.
val sharedPrefFile = context.getSharedPreferences(
"com.example.helloworld.USER_INFO",
Context.MODE_PRIVATE
)
val editor = sharedPrefFile.edit()
editor.clear()
editor.apply()
Note that when committing back to the preferences, the remove() and clear() are called first, regardless of whether you called them before or after put methods on the editor.
getPreferences():
Android provides getPreferences() which is an alternative to getSharedPreferences() method.
public SharedPreferences getPreferences (int mode)
This is useful when you want to create a preference file that is private to an Activity. The file name is the same as the Activity‘s class name.
Is Android shared preferences secure?
If you want to encrypt key and value pairs, use EncryptedSharedPreferences API.
This is all about Shared Preferences in Android. I hope you have learned something new. If you have any doubt, comment below.
Related: