Shared Preferences - Save, edit, retrieve, delete in Kotlin?

Kotlin Apps/ApplicationsMobile Development

This example demonstrates how Save, edit, retrieve, delete shared preference data in Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="8dp"
   tools:context=".MainActivity">
   <Button
      android:id="@+id/btnSave"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentStart="true"
      android:layout_centerInParent="true"
      android:onClick="saveData"
      android:text="Save" />
   <Button
      android:id="@+id/btnRetrieve"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_centerHorizontal="true"
      android:onClick="readData"
      android:text="Read" />
   <Button
      android:id="@+id/btnClear"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentEnd="true"
      android:layout_centerInParent="true"
      android:onClick="clearData"
      android:text="Clear" />
   <EditText
      android:id="@+id/etEmail"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@+id/etName"
      android:layout_alignParentEnd="true"
      android:layout_marginTop="10dp"
      android:ems="10"
      android:hint="Email"
      android:inputType="textEmailAddress" />
   <EditText
      android:id="@+id/etName"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignStart="@+id/etEmail"
      android:layout_marginTop="40dp"
      android:ems="10"
      android:hint="Name"
      android:inputType="text" />
   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="400dp"
      android:layout_below="@+id/btnSave"
      android:layout_marginTop="10dp"
      android:orientation="vertical"
      android:padding="8dp">
   <TextView
      android:id="@+id/textViewName"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="20dp"
      android:textColor="@android:color/holo_blue_light"
      android:textSize="24sp"
      android:textStyle="bold" />
   <TextView
      android:id="@+id/textViewEmail"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="10dp"
      android:textColor="@android:color/holo_blue_light"
      android:textSize="24sp"
      android:textStyle="bold">
   </LinearLayout>
</RelativeLayout>

Step 3 − Add the following code to src/MainActivity.kt

import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class MainActivity : AppCompatActivity() {
   var editTextName: EditText? = null
   var editTextEmail: EditText? = null
   lateinit var textViewName: TextView
   lateinit var textViewEmail: TextView
   private val myPreference = "myPref"
   private val name = "nameKey"
   private val email = "emailKey"
   var sharedPreferences: SharedPreferences? = null
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      editTextEmail = findViewById(R.id.etEmail)
      editTextName = findViewById(R.id.etName)
      sharedPreferences = getSharedPreferences(myPreference, Context.MODE_PRIVATE)
      if (sharedPreferences!!.contains(name)) {
         editTextName?.setText(sharedPreferences!!.getString(name, ""))
      }
      if (sharedPreferences!!.contains(email)) {
         editTextName?.setText(sharedPreferences!!.getString(email, ""))
      }
   }
   fun readData(view: View) {
      textViewEmail = findViewById(R.id.textViewEmail)
      textViewName = findViewById(R.id.textViewName)
      var strName: String = editTextName?.text.toString().trim()
      var strEmail: String = editTextEmail?.text.toString().trim()
      strName = sharedPreferences!!.getString(name, "")
      strEmail = sharedPreferences!!.getString(email, "")
      sharedPreferences = getSharedPreferences(myPreference, Context.MODE_PRIVATE)
      if (sharedPreferences!!.contains(name)) {
         textViewName.text = strName
      }
      if (sharedPreferences!!.contains(email)) {
         textViewEmail.text = strEmail
      }
      Toast.makeText(baseContext, "Data retrieved", Toast.LENGTH_SHORT).show()
   }
   fun saveData(view: View) {
      val strName: String = editTextName?.text.toString().trim()
      val strEmail: String = editTextEmail?.text.toString().trim()
      val editor: SharedPreferences.Editor = sharedPreferences!!.edit()
      editor.putString(name, strName)
      editor.putString(email, strEmail)
      editor.apply()
      Toast.makeText(baseContext, "Saved", Toast.LENGTH_SHORT).show()
   }
   fun clearData(view: View) {
      editTextName!!.text.clear()
      editTextEmail!!.text.clear()
      textViewName.text = ""
      textViewEmail.text = ""
      Toast.makeText(baseContext, "Cleared data", Toast.LENGTH_SHORT).show()
   }
}

Step 4 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.kotlipapp">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Click here to download the project code.

raja
Published on 20-Apr-2020 13:39:58
Advertisements