This post is intended for the beginners who want to store, a minimal amount of application-specific data using SharedPreferences API in Android. The available codebase is written in Java.
Storing relevant pieces of data is the most common use case we used in most of the application. The file system used in Android provides multiple options for us to save your app data. In this article, we’ll use the SharedPreferences API for reading and writing data.
The SharedPreferences API allows us to store the data in the form of key-value pairs similar to a Map. Each SharedPreferences object reference a file, which contains the key-value pairs and provides methods to read and write them.
All these SharedPreferences files is taken care of by the framework and it can be private or shared, the scope is defined during the object initialisation. The stored data will persist even when the user exits from the application. The data lost is happening only when the user uninstalls the application or performing clear data functionality.
With this article, you will learn everything that you need to know about the SharedPreferences API. I will try to be as much detail as possible and will break down this tutorial to multiple steps for better understanding.
- Initialise the SharedPreferences
- Write to SharedPreferences
- Read from SharedPreferences
- Remove data from SharedPreferences
- Wipe out the data from SharedPreferences
- Locating the source file
1. Initialise the SharedPreferences:
We can create a new application-specific SharedPreferences file or access an existing one by calling the getSharedPreferences() method with the help of the file name.
FILE_NAME – Uniquely identifiable filename
MODE – Operating Mode(MODE_PRIVATE, MODE_APPEND, MODE_ENABLE_WRITE_AHEAD_LOGGING)
For example, the below code snippet used to accesses the SharedPreferences file that is identified by the file name and opens it using the private mode so the file is accessible by only our app:
2. Write to SharedPreferences:
To write a key-value pair in SharedPreferences file, create an instance of SharedPreferences.Editor by calling edit() on your SharedPreferences object.
To set the values, call methods such as putInt(), putString(), providing the key and the value. For example:
commit() and apply() methods used to writes the updates to disk. After playing with this I felt, it is important to write difference between commit() and apply()
commit() – return true if value saved successfully otherwise false. It save values to SharedPreferences synchronously.
apply() – doesn’t return any value either on success or failure. Commits the changes to the in-memory SharedPreferences immediately which is asynchronous commit.
Note: If we don’t care about the return value from the write action and we’re initiating this from application’s main thread, then we can consider using apply().
3. Read from SharedPreferences:
To read the already stored values from the existing SharedPreferences file, we can make use of the methods such as getInt(), getString(), by specifying the key for the value, and also we can optionally set a default value to return if the key isn’t exists. For example:
4. Remove data from SharedPreferences:
To remove the specific key from the SharedPreferences file, we can use the method remove().
5. Wipe out the data from SharedPreferences:
Wiping out the entire cached data during the logout or some other specific scenarios is most common process in mobile applications. To wipe out the entire SharedPreferences file, we can use the method clear().
6. Locating the source file
Android stores SharedPreferences file as XML file in shared_prefs folder under DATA directory.
We can use Device File Explorer in Android Studio to check them.
That’s all… For real… Now we can use the SharedPreferences API to store the values locally into our application.
The source code is available on GitHub, use the below links to get the sample code.
Here is where things end for me and start for you.
Android doesn’t recommend saving confidential information in SharedPreferences without proper security. Encrypting the data while saving it locally is the easiest way to increase the safety of the data.
Encryption and Decryption along with SharedPreference deserves a separate blog post. I’m planning to write one soon. Keep watching this space for updates.
Latest posts by Jaison Fernando (see all)
- Phone number auth using Firebase Authentication SDK - March 20, 2020
- Password-less email auth using Firebase Authentication SDK - March 9, 2020
- How to use SharedPreferences API in Android? - February 10, 2020