Android SharedPreferences Tutorial in Kotlin

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 “daniel@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 articles, weather, username, password, first_name, or something else.

package com.example.sharedpreferences

import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        val sharedPreferences = getSharedPreferences("production", Context.MODE_PRIVATE)
        sharedPreferences.edit().putString("email_address", "danieljmalone@gmail.com").apply()
    }
}

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.

Saving a value with Kotlin in Android Studio.

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.

package com.example.sharedpreferences

import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log.d
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        val sharedPreferences = getSharedPreferences("production", Context.MODE_PRIVATE)
        sharedPreferences.edit().putString("email_address", "danieljmalone@gmail.com").apply()

        val savedEmailAddress = sharedPreferences.getString("email_address", "")

        d("daniel", "savedEmailAddress is: $savedEmailAddress")
    }
}

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.

But there are some tricks for saving a lot of data to SharedPreferences. Using the .apply lambda we can save multiple values with less code all things to Kotlin. When saving a user’s email, phone, address, age and city we can simply write the following.

        val sharedPreferences = getSharedPreferences("production", Context.MODE_PRIVATE)
        sharedPreferences.edit().apply {
            putString("emailAddress", "danieljmalone@gmail.com")
            putString("phoneNumber", "512-483-4863")
            putInt("age", 28)
            putString("address", "129 West 4th St. Apt. 1543")
            putString("city", "Austin")
        }.apply()

That’s it! We’ve successfully saved a String to SharedPreferences.

Daniel Malone Daniel Malone
Bringing more than a decade of software engineering experience, Daniel Malone is Editor at androidEveryday. An Austin native, Daniel is often found reading technical books, blogging and creating YouTube tutorials. When not working, he likes to listen to pop hits on Google Play Music.

Android RecyclerView Tutorial (Part 1)

  • Most apps contain lists of data using RecyclerView.
  • In this tutorial, use ConstraintLayout and Kotlin to display a list of data.

1 year ago

findViewById() in Kotlin

  • As you may have discovered, findViewByid() is no longer needed.
  • Kotlin adds the ability to directly access Views.

1 year ago

Android Architecture Components Tutorial: ViewModel + LiveData

  • Use Kotlin to build a basic Android app using Android Architecture Components.
  • As part of Jetpack, LiveData and ViewModel support a MVVM app architecture.

1 year ago

Cleaner Architecture for Android Apps

  • Clean Architecture for Android can help developers prepare for change.
  • But app developers can't possibly know what will change.

    1 year ago

Android RecyclerView with Kotlin – Part 3

  • In part three of this series, finish creating the RecyclerView.
  • Use onBindViewHolder to display data.

1 year ago

Android RecyclerView with Kotlin – Part 2

  • Create the entire RecylerView for our UsersAdapter.
  • Continued from part 1, where we set up the Android Studio project.

1 year ago

Android and RxJava: Using a Single

  • Use RxJava's Single class when the expected type is either a success or error.
  • It's only slightly different from Observable.just(), which we discussed in the last article.

1 year ago

Android and RxJava: Getting Started

  • The powerful library RxJava can help developers build better apps.
  • See how to use Observables and Observers in this tutorial.

1 year ago

Android RecyclerView with Kotlin - Part 1

  • Oftentimes, developers need to display a list of some sort of data.
  • Whatever type of data is displayed, you should use a RecyclerView.

1 year ago

Display Sample Data when Creating a RecyclerView

  • Android Studio's default RecyclerView preview lacks sample data.
  • Adding sample data can be helpful for debugging.

1 year ago

Android Studio Tutorial with Kotlin (2018 Edition) - Part 2

  • Create a UI in Android Studio using the Design mode.
  • In this latest installment for beginners, we'll add a widget to our screen.

1 year ago