How to work with Shared Preferences in Android Studio using Kotlin.
Learn how to work with Shared Preferences in Android Studio using Kotlin for storing data persistently. Explore examples and best practices at RRTutors.
In this android example, we will see how to work with shared preferences in Android Studio by using Kotlin Language. SharedPreferences is an interface for accessing and updating preference data. It deals with objects that point to a file containing key-value pairs and provides methods for reading and writing them. SharedPreferences can be used to store basic types (Int, Float, Long, Boolean, String, and Set of Strings).
Implementation:
Step 1: Create a new Project in android studio.
| Go to File > New > New Project > Empty Activity > Next > Enter Name > Select Language Kotlin > Finish |
Step 2: Go to activity_main.xml file and add the following code
|
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" <EditText <Button <Button |
Step 3: Open MainActivity.kt file and add the following code.
|
lateinit var shared : SharedPreferences override fun onCreate(savedInstanceState: Bundle?) { shared = getSharedPreferences("Test" , Context.MODE_PRIVATE)
save.setOnClickListener { show.setOnClickListener { txt.text = shared.getString("txt" , "No imported" ) }
|
Step 4: Run the app on emulator or real device, you will get the output as given below
OUTPUT:
![]() |
![]() |
Complete Source Code of Shared Preferences Example :
activity_main.xml file
|
<?xml version="1.0" encoding="utf-8"?> <EditText <Button <Button |
MainActivity.kt file
|
import android.content.Context class SPActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { shared = getSharedPreferences("Test" , Context.MODE_PRIVATE)
save.setOnClickListener { show.setOnClickListener { txt.text = shared.getString("txt" , "No imported" ) }
|
Conclusion: In this article we have covered how to deal with Shared Preferences in Android Studio by using Kotlin Language.

