Android SharedPreferences is store key-value (String, Integer, Boolean, etc) Paris data. SharedPreferences object points to a file holding a key-value
SharedPreferences usually use to 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 the 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 used for multiple shared preference files and it can be identified by name. For call, this has to use any Context of your app.- getPreferences() – Retrieve a default shared preferences file from the Activity (belong to the activity). It uses 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 to 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)
getPreferences()
if you need just one shared preference file for your activity.
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 yourSharedPreferences
, 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() }
Pass the keys and values you want to write with methods for example : putInt()
and putString()
. Then call apply()
orcommit()
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", "")
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>
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() } }
Step 4. Now Run the application, in emulator or On you android device
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