Shared Preferences in Android: Kotlin Tutorial

I have already explained in my previous articles on how can we store and access data in Android:

Now we will see how can we use Shared Preferences for storing application data. Whenever you want to store user-specific data such his personal details etc, we can make use of Shared Preferences. Shared Preferences are advisable whenever you collect data on the first launch of the application and store it so that it can be used during further launches or in other activities.

We will be using Kotlin in this tutorial, so if you are new to Kotlin, then in my previous post I have explained in detail on how to get started with Kotlin for Android.

Creating new Project

Open Android Studio and create a new project named “Shared Preferences”. Don’t forget to select “Include Kotlin support” while creating the project.

In this tutorial, we will be seeing how can we store your name, phone number and email id using Shared Preferences. For this let’s create 3 textboxes and 1 submit button in activity_main.xml:

Below is how the app looks when you launch it for the first time:

Shared preferences in Android - First Launch

We’ll store the necessary strings used in the application in string.xml

When the user submits the details and re-launches the app, then we will show the user details. For this, we will use the following layout:

Using Kotlin Android Extensions

In order to simplify accessing views from layouts, we can make use of Kotlin Android Extensions. Kotlin Android Extensions are automatically included in build.gradle file when you include Kotlin support. In order to reference views in activity_main.xml, use the following import:

The contents of EditText can be accessed and changed as shown below:

Storing and Accessing data from Shared Preferences

We call the method getSharedPreferences(String name, int mode) to get access to Shared Preferences.

Save the data in Shared Preferences as follows:

We can access the saved data as shown below:

The Complete MainActivity.kt file

Below is the complete Kotlin file used to store and access the data:

If you have any doubts you can ask them in the comments section. If you liked this article then please follow AndroidDeft on Twitter and Facebook.

Download Source CodeDownload APK

Shared Preferences in Android Demo - Shared Preferences in Android: Kotlin Tutorial

Stay Connected

No spam guarantee.

Abhishek

Abhishek

Abhishek loves coding. His favorite is Android Development. Apart from coding he loves traveling and reading.
Abhishek

Leave a Reply

Your email address will not be published. Required fields are marked *