In this tutorial
Here w are going to learn how to create a simple custom SharedPreferences.kt class that can be used to every Android application if needed.
Overview
In many cases, we have to use SharedPreferences in our Application such as to store login status, save user-specific data and save application settings.
SharedPreferences is Application specific, so data stored in SharedPreferences can be lost in the following situations
- By Uninstalling the Application
- By Clearing application data (Using device settings)
Storing Data with SharedPreferences
Let’s start with the custom SharedPreference.kt class. Create a Kotlin class And Initialise SharedPreferences as shown below.
package com.kotlincodes.sharedpreferenceswithkotlin import android.content.Context import android.content.SharedPreferences /** * Created by Kolincodes on 10/05/2018. */ class SharedPreference(val context: Context) { private val PREFS_NAME = "kotlincodes" val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) }
PREF_NAME is the name of preference file.
Storing Data
To store String, Int and Boolean data we have three methods with the same name and different parameters (Method overloading). Add these methods to your SharedPreference.kt class.
To Store String data
fun save(KEY_NAME: String, value: Int) { val editor: SharedPreferences.Editor = sharedPref.edit() editor.putInt(KEY_NAME, value) editor.commit() }
To Store Int data
fun save(KEY_NAME: String, value: Int) { val editor: SharedPreferences.Editor = sharedPref.edit() editor.putInt(KEY_NAME, value) editor.commit() }
To Store Boolean data
fun save(KEY_NAME: String, status: Boolean) { val editor: SharedPreferences.Editor = sharedPref.edit() editor.putBoolean(KEY_NAME, status!!) editor.commit() }
Retrieve Data
To Retrieve the data stored in SharedPreferences use the following methods.
To Retrieve String
fun getValueString(KEY_NAME: String): String? { return sharedPref.getString(KEY_NAME, null) }
To Retrieve Int
fun getValueInt(KEY_NAME: String): Int { return sharedPref.getInt(KEY_NAME, 0) }
To Retrieve Boolien
fun getValueString(KEY_NAME: String): String? { return sharedPref.getString(KEY_NAME, null) }
Remove and Clear
To clear the entire SharedPreferences use the below code
fun clearSharedPreference() { val editor: SharedPreferences.Editor = sharedPref.edit() //sharedPref = PreferenceManager.getDefaultSharedPreferences(context); editor.clear() editor.commit() }
To remove a specific data
fun removeValue(KEY_NAME: String) { val editor: SharedPreferences.Editor = sharedPref.edit() editor.remove(KEY_NAME) editor.commit() }
Now we are almost done with all the methods inside our SharedPreference.kt class.
Please find the Complete code for SharedPreference.kt file below.
SharedPreference.kt
package com.kotlincodes.sharedpreferenceswithkotlin import android.content.Context import android.content.SharedPreferences /** * Created by Kolincodes on 10/05/2018. */ class SharedPreference(val context: Context) { private val PREFS_NAME = "kotlincodes" val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) fun save(KEY_NAME: String, text: String) { val editor: SharedPreferences.Editor = sharedPref.edit() editor.putString(KEY_NAME, text) editor!!.commit() } fun save(KEY_NAME: String, value: Int) { val editor: SharedPreferences.Editor = sharedPref.edit() editor.putInt(KEY_NAME, value) editor.commit() } fun save(KEY_NAME: String, status: Boolean) { val editor: SharedPreferences.Editor = sharedPref.edit() editor.putBoolean(KEY_NAME, status!!) editor.commit() } fun getValueString(KEY_NAME: String): String? { return sharedPref.getString(KEY_NAME, null) } fun getValueInt(KEY_NAME: String): Int { return sharedPref.getInt(KEY_NAME, 0) } fun getValueBoolien(KEY_NAME: String, defaultValue: Boolean): Boolean { return sharedPref.getBoolean(KEY_NAME, defaultValue) } fun clearSharedPreference() { val editor: SharedPreferences.Editor = sharedPref.edit() //sharedPref = PreferenceManager.getDefaultSharedPreferences(context); editor.clear() editor.commit() } fun removeValue(KEY_NAME: String) { val editor: SharedPreferences.Editor = sharedPref.edit() editor.remove(KEY_NAME) editor.commit() } }
Implement in our Application
N
The Image below Shows the Final output of the project

Setup Layout
The Layout for our MainActivity.kt class is shown below.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_margin="12dp" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" tools:context=".MainActivity"> <EditText android:id="@+id/edt_name" android:layout_margin="6dp" android:hint="Name" android:layout_width="match_parent" android:layout_height="wrap_content" /> <EditText android:id="@+id/edt_email" android:layout_margin="6dp" android:hint="Email" android:layout_width="match_parent" android:layout_height="wrap_content" /> <LinearLayout android:layout_marginTop="12dp" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/btn_save" android:layout_weight="1" android:text="Save" android:layout_width="0dp" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_retriev" android:layout_weight="1" android:text="Retrieve" android:layout_width="0dp" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_clear" android:layout_weight="1" android:text="Clear" android:layout_width="0dp" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout>
Setup MainActivity
Our Application have only one page with two EditText and Three Button.
First we Initialize our SharedPreferece.kt class in our MainActivity by
val sharedPreference:SharedPreference=SharedPreference(this)
On Save button click We stores EditText values into SharedPreferences.
On Retrieve Button click we Retrieve the saved data from SharedPreferences and set this data as the EditText hint.
On Clear button click we clear all the data from shared preferences.
Our MainActivity.kt class is given below.
package com.kotlincodes.sharedpreferenceswithkotlin import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast class MainActivity : AppCompatActivity() { lateinit var edtName:EditText lateinit var edtEmail:EditText lateinit var btnSave:Button lateinit var btnRetrive:Button lateinit var btnClear:Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sharedPreference:SharedPreference=SharedPreference(this) edtName=findViewById(R.id.edt_name) edtEmail=findViewById(R.id.edt_email) btnClear=findViewById(R.id.btn_clear) btnSave=findViewById(R.id.btn_save) btnRetrive=findViewById(R.id.btn_retriev) btnSave.setOnClickListener { val name=edtName.editableText.toString() val email=edtEmail.editableText.toString() sharedPreference.save("name",name) sharedPreference.save("email",email) Toast.makeText(this@MainActivity,"Data Stored",Toast.LENGTH_SHORT).show() //to save an Int // sharedPreference.save("intval",1) //to save boolien // sharedPreference.save("bool",true) } btnRetrive.setOnClickListener { if (sharedPreference.getValueString("name")!=null) { edtName.hint = sharedPreference.getValueString("name")!! Toast.makeText(this@MainActivity,"Data Retrieved",Toast.LENGTH_SHORT).show() }else{ edtName.hint="NO value found" } if (sharedPreference.getValueString("email")!=null) { edtEmail.hint = sharedPreference.getValueString("email")!! }else{ edtEmail.hint="No value found" } } btnClear.setOnClickListener { sharedPreference.clearSharedPreference() Toast.makeText(this@MainActivity,"Data Cleared",Toast.LENGTH_SHORT).show() } } }
That’s it! Now run the project!
The full source code is available here.
Thanks for reading!