How to Save And Get Data From Shared Preferences in Kotlin

In this article, we will learn how to save and get data from the Shared Preferences. Android Shared Preferences allow the Apps to store data in it and retrieve data in the form of keys and value. The application data should be kept until the application is deleted.

Basic Method to Save & Retrieve Data in SharedPreferences in Kotlin

Initializing in the shared Preferences

val sharedPreferences: SharedPreferences = this.getSharedPreferences(sharedPrefFile, Context.MODE_PRIVATE)

Save Data in the SharedPreferences

editor.putInt("age_key", age)
editor.putString("nameFirst_key", namefirst)
editor.putString("nameLast_key", namelast)
editor.apply()
editor.commit()

Retrieve Data in the SharedPreferences

outputFirstName.setText(sharedNameFirstValue).toString()
outputLastName.setText(sharedNameLastValue).toString()
outputAge.setText(sharedAgeValue.toString())

At the end of this tutorial, you will see the following screen will be designed.

Save And Get Data From Shared Preferences

To store the App data in the form of the XML file, Android Apps use Shared Preferences. The Shared Preferences file is under the directory data/data/{application package}/share_prefs. In order to access the common preferences in your application, we need to get an example using one of the following methods.

getPreferences()
getSharedPreferences()
getDefaultSharedPreferences()

val sharedPreferences: SharedPreferences = this.getSharedPreferences(String preferences_fileName,int mode)

Here the preference_file_name is the name of the common preferences file and the file format is the operational mode. To delete the preferences data of the application we call the following methods.

editor.remove(“key”)It removes the specific key values
editor.clear()It removes all preferences data

Example of SharedPreferences

In this example, we will get the input data (firstName, lastName, and age) from EditText and store them in a preference file. When you click the button then you can retrieve and display data in the TextView by performing the setOnClickListener() and can clear the preferences data.

Save And Get Data From Shared Preferences in Kotlin

Activity Main XML Code

Add the following code in the activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TableLayout
    android:layout_width="368dp"
    android:layout_height="495dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <TableRow>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="0"
            android:layout_marginLeft="10sp"
            android:layout_marginStart="10sp"
            android:text="First Name"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

        <EditText
            android:id="@+id/firstName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="1"
            android:layout_marginLeft="50sp"
            android:layout_marginStart="50sp"
            android:hint="First Name"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="0"
            android:layout_marginLeft="10sp"
            android:layout_marginStart="10sp"
            android:text="Last Name"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

        <EditText
            android:id="@+id/lastName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="1"
            android:layout_marginLeft="50sp"
            android:layout_marginStart="50sp"
            android:hint="Last Name"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
    </TableRow>
    <TableRow>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="0"
            android:layout_marginLeft="10sp"
            android:layout_marginStart="10sp"
            android:text="Enter Age"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

        <EditText
            android:id="@+id/editAge"
            android:layout_width="201dp"
            android:layout_height="wrap_content"
            android:layout_column="1"
            android:layout_marginLeft="50sp"
            android:layout_marginStart="50sp"
            android:hint="Age"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
    </TableRow>

    <TableRow android:layout_marginTop="60dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="0"
            android:layout_marginLeft="10sp"
            android:layout_marginStart="10sp"
            android:text="Your Age"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

        <TextView
            android:id="@+id/textViewShowAge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="1"
            android:layout_marginLeft="50sp"
            android:layout_marginStart="50sp"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
    </TableRow>

    <TableRow android:layout_marginTop="20dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="0"
            android:layout_marginLeft="10sp"
            android:layout_marginStart="10sp"
            android:text="First Name"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

        <TextView
            android:id="@+id/textViewShowFirstName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="1"
            android:layout_marginLeft="50sp"
            android:layout_marginStart="50sp"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
    </TableRow>
    <TableRow android:layout_marginTop="20dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="0"
            android:layout_marginLeft="10sp"
            android:layout_marginStart="10sp"
            android:text="Last Name"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

        <TextView
            android:id="@+id/textViewShowLastName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="1"
            android:layout_marginLeft="50sp"
            android:layout_marginStart="50sp"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
    </TableRow>
</TableLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:orientation="vertical"
    android:gravity="center"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent">

    <Button
        android:id="@+id/save"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Save" />

    <Button
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="View" />

    <Button
        android:id="@+id/clear"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Clear" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity Code in Kotlin

Add the following code to MainActivty.kt. In this class, we store the shared preferences data in the form of key-value in shared preference.

package com.example.handyopinion_sharedpreferences


import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


internal class MainActivity : AppCompatActivity() {

    val sharedPrefFile = "kotlinsharedpreference"

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

        val inputAge = findViewById<EditText>(R.id.editAge)
        val inputFirstName = findViewById<EditText>(R.id.firstName)
        val inputLastName = findViewById<EditText>(R.id.lastName)
        val outputAge = findViewById<TextView>(R.id.textViewShowAge)
        val outputFirstName = findViewById<TextView>(R.id.textViewShowFirstName)
        val outputLastName = findViewById<TextView>(R.id.textViewShowLastName)

        val btnSave = findViewById<Button>(R.id.save)
        val btnView = findViewById<Button>(R.id.view)
        val btnClear = findViewById<Button>(R.id.clear)
        val sharedPreferences: SharedPreferences = this.getSharedPreferences(sharedPrefFile, Context.MODE_PRIVATE)
        btnSave.setOnClickListener(View.OnClickListener {
            val age = Integer.parseInt(inputAge.text.toString())
            val namefirst: String = inputFirstName.text.toString()
            val namelast: String = inputLastName.text.toString()
            val editor = sharedPreferences.edit()
            editor.putInt("age_key", age)
            editor.putString("nameFirst_key", namefirst)
            editor.putString("nameLast_key", namelast)
            editor.apply()
            editor.commit()
        })
        btnView.setOnClickListener {
            val sharedAgeValue = sharedPreferences.getInt("age_key", 0)
            val sharedNameFirstValue = sharedPreferences.getString("nameFirst_key", "Handy")
            val sharedNameLastValue = sharedPreferences.getString("nameLast_key", "Opinion")
            if (sharedAgeValue.equals(0) && sharedNameFirstValue.equals("Handy")) {
                outputFirstName.setText("First Name: ${sharedNameFirstValue}").toString()
                outputAge.setText("default Age: ${sharedAgeValue.toString()}")
            }
            else if (sharedAgeValue.equals(0) && sharedNameLastValue.equals("Opinion")) {
                outputLastName.setText("Last Name: ${sharedNameLastValue}").toString()
                outputAge.setText("default Age: ${sharedAgeValue.toString()}")
            }
            else if (sharedAgeValue.equals(0) && sharedNameFirstValue.equals("Handy") && sharedNameLastValue.equals("Opinion") ) {
                outputFirstName.setText("First Name: ${sharedNameFirstValue}").toString()
                outputLastName.setText("Last Name: ${sharedNameLastValue}").toString()
                outputAge.setText("default Age: ${sharedAgeValue.toString()}")
            }
            else {
                outputFirstName.setText(sharedNameFirstValue).toString()
                outputLastName.setText(sharedNameLastValue).toString()
                outputAge.setText(sharedAgeValue.toString())
            }

        }
        btnClear.setOnClickListener(View.OnClickListener {
            val editor = sharedPreferences.edit()
            editor.clear()
            editor.apply()
            outputFirstName.setText("").toString()
            outputLastName.setText("").toString()
            outputAge.setText("")
        })
    }
}

That’s it. This is how to Save And Get Data From Shared Preferences in Kotlin.

Feel free to ask your questions or give suggestions in the comments section below.

Next Article

How to Save And Retrieve Class Object From Shared Preferences Using Gson Library in Kotlin Android Studio

Please share this post:
Posts created 41

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: