Android SharedPreferences is store key-value (String, Integer, Boolean, etc) Paris data. SharedPreferences object points to a file holding a key-value pairs and provides simple methods to read and write data. It can be private or shared.

SharedPreferences usually use for save a setting preference (push notification, alert, the default setting of the app, etc) or manage a login session in the app.

In this tutorial, you will learn following:

What is Android SharedPreferences and how to create it. Saving and Retrieving data in SharedPreferences in Kotlin.

Create Shared Preferences

For a creating or accessing an existing shared preference, you can use by calling one of a method:

getSharedPreferences() – this method use for multiple shared preference files and it can identified by name. For call this have to use any Context of your app.

– this method use for multiple shared preference files and it can identified by name. For call this have to use any of your app. getPreferences() – Retrieve a default shared preferences file form the Activity (belong the activity).Its use only one shared preference file for the activity.

getSharedPreferences()

When naming your shared preference files, you should use a name that’s uniquely identifiable to your app. An easy way to do this is prefix the file name with your application ID. For example: "com.example.myapp.PREFERENCE_FILE_KEY"

val sharedPref = activity?.getSharedPreferences( getString(R.string.preference_file_key), Context.MODE_PRIVATE) 1 2 val sharedPref = activity ? . getSharedPreferences ( getString ( R . string . preference_file_key ) , Context . MODE_PRIVATE )

getPreferences()

if you need just one shared preference file for your activity.

val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) 1 val sharedPref = activity ? . getPreferences ( Context . MODE_PRIVATE )

Note: The MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE modes have been deprecated since API level 17.

Write to shared preferences

You have call edit() on your SharedPreferences , To write to a shared preferences file.

val sharedPref = this.getPreferences(Context.MODE_PRIVATE) ?: return with(sharedPref.edit()) { putString("name", et_name.text.toString()) commit() } 1 2 3 4 5 val sharedPref = this . getPreferences ( Context . MODE_PRIVATE ) ? : return with ( sharedPref . edit ( ) ) { putString ( "name" , et_name . text . toString ( ) ) commit ( ) }

Pass the keys and values you want to write with methods for example : putInt() and putString() . Then call apply() or commit() to save the changes. For example:

Check this tutorial question number #2 : What is the difference between commit() and apply() method in SharedPreferences()?

Read from shared preferences

val sharedPref = this.getPreferences(Context.MODE_PRIVATE) ?: return val str_name = sharedPref.getString("name", "") 1 2 val sharedPref = this . getPreferences ( Context . MODE_PRIVATE ) ? : return val str_name = sharedPref . getString ( "name" , "" )

To retrieve values from a shared preferences file, call methods getInt() and getString() etc, providing the key for the value you want, and optionally a default value to return if the key isn’t present. For example:

Let’s Build a Simple Example of Android SharedPreferences :

Step 1. Create new project “ Build Your First Android App in Kotlin

Step 2. Add following code in “activity_main.xml” layout file

adding 2 TextView and 2 Button. Where button have method to perform a Click action.

<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.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"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Enter Details" android:textSize="16dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:ems="10" android:inputType="textPersonName" android:hint="Name" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> <EditText android:id="@+id/et_number" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:ems="10" android:hint="Number" android:inputType="phone" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_name" /> <Button android:id="@+id/btn_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:layout_marginStart="8dp" android:layout_marginTop="32dp" android:text="Save" android:onClick="saveData" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_number" /> <Button android:id="@+id/btn_get" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginRight="8dp" android:layout_marginTop="32dp" android:text="Get" android:onClick="getData" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_number" /> </android.support.constraint.ConstraintLayout> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 <? xml version = "1.0" encoding = "utf-8" ?> < android . support . constraint . 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" > < TextView android : id = "@+id/textView" android : layout_width = "wrap_content" android : layout_height = "wrap_content" android : layout_marginTop = "16dp" android : text = "Enter Details" android : textSize = "16dp" app : layout_constraintLeft_toLeftOf = "parent" app : layout_constraintRight_toRightOf = "parent" app : layout_constraintTop_toTopOf = "parent" / > < EditText android : id = "@+id/et_name" android : layout_width = "match_parent" android : layout_height = "wrap_content" android : layout_margin = "8dp" android : ems = "10" android : inputType = "textPersonName" android : hint = "Name" app : layout_constraintEnd_toEndOf = "parent" app : layout_constraintStart_toStartOf = "parent" app : layout_constraintTop_toBottomOf = "@+id/textView" / > < EditText android : id = "@+id/et_number" android : layout_width = "match_parent" android : layout_height = "wrap_content" android : layout_margin = "8dp" android : ems = "10" android : hint = "Number" android : inputType = "phone" app : layout_constraintEnd_toEndOf = "parent" app : layout_constraintStart_toStartOf = "parent" app : layout_constraintTop_toBottomOf = "@+id/et_name" / > < Button android : id = "@+id/btn_save" android : layout_width = "wrap_content" android : layout_height = "wrap_content" android : layout_marginLeft = "8dp" android : layout_marginStart = "8dp" android : layout_marginTop = "32dp" android : text = "Save" android : onClick = "saveData" app : layout_constraintStart_toStartOf = "parent" app : layout_constraintTop_toBottomOf = "@+id/et_number" / > < Button android : id = "@+id/btn_get" android : layout_width = "wrap_content" android : layout_height = "wrap_content" android : layout_marginEnd = "8dp" android : layout_marginRight = "8dp" android : layout_marginTop = "32dp" android : text = "Get" android : onClick = "getData" app : layout_constraintEnd_toEndOf = "parent" app : layout_constraintTop_toBottomOf = "@+id/et_number" / > < / android . support . constraint . ConstraintLayout >

Step 3. Open the “MainActivity.kt” and add following code

In this code doing action by clicking button. Saving and getting data with same key.

package `in`.eyehunt.sharedpreferences import android.content.Context import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } //saving data fun saveData(view: View) { val sharedPref = this.getPreferences(Context.MODE_PRIVATE) ?: return with(sharedPref.edit()) { putString("name", et_name.text.toString()) putInt("number", et_number.text.toString().toInt()) commit() } } fun getData(view: View) { val sharedPref = this.getPreferences(Context.MODE_PRIVATE) ?: return val str_name = sharedPref.getString("name", "") val int_number = sharedPref.getInt("number", 0) Toast.makeText(this, "$str_name $int_number", Toast.LENGTH_LONG).show() } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 package ` in ` . eyehunt . sharedpreferences import android . content . Context import android . support . v7 . app . AppCompatActivity import android . os . Bundle import android . view . View import android . widget . Toast import kotlinx . android . synthetic . main . activity_main . * class MainActivity : AppCompatActivity ( ) { override fun onCreate ( savedInstanceState : Bundle ? ) { super . onCreate ( savedInstanceState ) setContentView ( R . layout . activity_main ) } //saving data fun saveData ( view : View ) { val sharedPref = this . getPreferences ( Context . MODE_PRIVATE ) ? : return with ( sharedPref . edit ( ) ) { putString ( "name" , et_name . text . toString ( ) ) putInt ( "number" , et_number . text . toString ( ) . toInt ( ) ) commit ( ) } } fun getData ( view : View ) { val sharedPref = this . getPreferences ( Context . MODE_PRIVATE ) ? : return val str_name = sharedPref . getString ( "name" , "" ) val int_number = sharedPref . getInt ( "number" , 0 ) Toast . makeText ( this , "$str_name $int_number" , Toast . LENGTH_LONG ) . show ( ) } }

Step 4. Now Run the application, in emulator

Output screenshot Android SharedPreferences example :

Download source code Android SharedPreferences in kotlin

https://github.com/EyeHunts/SharedPreferences

Note: This example (Project) is developed in Android Studio 3.1.3. Tested on Android 9 ( Android-P), compile SDK version API 27: Android 8.0 (Oreo) MinSdkVersion=”15″ TargetSdkVersion=”27″ Coding in Kotlin

Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.

Share this: Facebook

WhatsApp

LinkedIn

More

Twitter

Print



Reddit

Tumblr



Pinterest

Pocket



Telegram

Skype



Email

