Saving data across app launches and terminations is easy.
SharedPreferences is good for storing small amounts of data, such as a username (
String) and password (
String). For example, if you are building an Android app that saves the user’s email address and password,
SharedPreferences can be used to store the email and password. Under normal conditions, setting a variables to “email@example.com” and “password1234” will function when the app is open, but not if the user navigates to another app then back to your app.
SharedPreferences is good for storing info like an email and password. It’s fast, reliable and performant. With only 2 lines of code, we can save and retrieve data throughout the app in milliseconds.
But what is it not good for? Large amounts of structure data. For example,
SharedPreferences is not good for storing product data in your Ecommerce app or podcasting app. For structured data like an Excel spreadsheet, Room is a viable option. For storing audio and video files, device storage should be utilized. It’s probably best not to store
JSON, although it certainly can be used to store JSON, which can be complimented with the
GSON library by Google.
With that, let’s begin by saving a value that can be retrieved throughout the app. First we call
getSharedPreferences, passing it a file name and read/write mode. For the file name, I’ve chosen
production, but you can call it
first_name, or something else.
Then we call
edit() on the
SharedPreferences variable, passing in a key and value. The key is the field name, and the value is the data to be saved. In this case, an email address.
If you run the code, it successfully saves the email address to local storage. Now let’s see how we can retrieve the email address.
With only one line of code, we can get the saved
email_address. On line 21 above, we output
savedEmailAddress to the
Logcat console for testing.
That’s it! We’ve successfully saved a