SharedPreferences - Android Studio - Kotlin

How to use SharedPreferences using Android Studio with Kotlin

SharedPreferences in Android Studio is one of the simplest and most commonly used ways to store small amounts of data on Android devices. It allows you to save values in the form of key–value pairs, making it ideal for storing lightweight and persistent data such as user settings, app preferences, login states, theme choices, and more.

SharedPreferences supports saving the following data types: String, int, boolean, long, float, and Set<String>. Because it is lightweight and fast, it is recommended when you need to store a small collection of simple key-value data.

Using SharedPreferences, you can easily addupdate, and remove stored values without needing complex storage solutions like databases.

To access SharedPreferences in Android, you can use any of the following APIs depending on your requirement:

  • getPreferences() – Accesses preferences that belong to a single Activity. Useful when the data is specific to that Activity only.

  • getSharedPreferences() – Accesses application-wide shared preferences from any Activity or Context. Best for global values used across the app.

  • getDefaultSharedPreferences() – Accesses the default preference file used by Android’s PreferenceManager, commonly used when working with the settings screen or Android's preference framework.

SharedPreferences offers a simple and efficient way to store persistent data, making it a must-know feature for every Android developer.

>> Check For Java

Code:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="20dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Shared Preferences"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/nameEt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Name"
        android:inputType="textPersonName|textCapWords" />

    <EditText
        android:id="@+id/ageEt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Age"
        android:inputType="date" />

    <EditText
        android:id="@+id/emailEt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Email"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/passwordEt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:inputType="textPassword" />

    <CheckBox
        android:id="@+id/rememberCb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Remember" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/saveBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Save" />

</LinearLayout>

MainActivity.kt

package com.technifysoft.myapplication

import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.widget.CheckBox
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.button.MaterialButton

class MainActivityKt : AppCompatActivity() {

    private lateinit var nameEt: EditText
    private lateinit var ageEt: EditText
    private lateinit var emailEt: EditText
    private lateinit var passwordEt: EditText
    private lateinit var rememberCb: CheckBox
    private lateinit var saveBtn: MaterialButton

    //variables
    private var name: String? = null
    private var email: String? = null
    private var password: String? = null
    private var age = 0
    private var isRemembered = false

    //shared pref
    private lateinit var sharedPreferences: SharedPreferences
    private lateinit var spEditor: SharedPreferences.Editor

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

        //init views
        nameEt = findViewById(R.id.nameEt)
        ageEt = findViewById(R.id.ageEt)
        emailEt = findViewById(R.id.emailEt)
        passwordEt = findViewById(R.id.passwordEt)
        rememberCb = findViewById(R.id.rememberCb)
        saveBtn = findViewById(R.id.saveBtn)

        //init share pref
        sharedPreferences = getSharedPreferences("USER_INFO_SP", Context.MODE_PRIVATE)

        //get data from shared preferences
        name = sharedPreferences.getString("NAME", "")
        age = sharedPreferences.getInt("AGE", 0)
        email = sharedPreferences.getString("EMAIL", "")
        password = sharedPreferences.getString("PASSWORD", "")
        isRemembered = sharedPreferences.getBoolean("REMEMBER", false)

        //set data to views
        nameEt.setText(name)
        ageEt.setText("" + age)
        emailEt.setText(email)
        passwordEt.setText(password)
        rememberCb.setChecked(isRemembered)

        //click to input data from views
        saveBtn.setOnClickListener(View.OnClickListener {
            //get data from views
            name = "" + nameEt.getText().toString().trim()
            age = ageEt.getText().toString().trim().toInt()
            email = "" + emailEt.getText().toString().trim()
            password = "" + passwordEt.getText().toString().trim()
            if (rememberCb.isChecked) {
                isRemembered = true
                //save data to shared preferences
                spEditor = sharedPreferences.edit()
                spEditor.putString("NAME", name)
                spEditor.putInt("AGE", age)
                spEditor.putString("EMAIL", email)
                spEditor.putString("PASSWORD", password)
                spEditor.putBoolean("REMEMBER", true)
                spEditor.apply()
                Toast.makeText(this, "Info is remembered...", Toast.LENGTH_SHORT).show()
            } else {
                isRemembered = false
                //don't save | remove data from shared preferences
                spEditor = sharedPreferences.edit()
                spEditor.clear()
                spEditor.apply()
                Toast.makeText(this, "Info is not remembered...", Toast.LENGTH_SHORT).show()
            }
        })
    }
}

Screenshots:

Comments

Popular posts from this blog

Picture In Picture - Android Studio - Kotlin

Manage External Storage Permission - Android Studio - Kotlin

SeekBar with Customization | Android Studio | Java