Optimal Data Handling in Android Apps with SharedPreferences and Kotlin

Discover in our latest blog post how you can leverage the powerful functionality of Android SharedPreferences using Kotlin. From basic implementation to efficient data management – explore concise tips and tricks to optimize your Android apps.

What are Android SharedPreferences?

SharedPreferences has been part of the Android API since API level 1. It is an interface that allows us to store/modify/delete data locally. Generally, it is used to cache user-specific local data such as login forms. The data is stored in the form of a key-value pair. Multiple files can be created to hold the SharedPreferences data.

Methods of SharedPreferences

Let’s look at some important methods for SharedPreferences.

  • The getSharedPreferences(String, int) method is used to retrieve an instance of SharedPreferences. Here, String is the name of the SharedPreferences file, and int is the passed context.
  • The SharedPreferences.Editor() is used to edit values in the SharedPreferences.
  • We can call commit() or apply() to save the values in the SharedPreferences file. commit() saves the values immediately, while apply() saves the values asynchronously.

Setting/Retrieving SharedPreferences Values with Kotlin

We can set values on our SharedPreferences instance using Kotlin as follows:

val sharedPreference = getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE)
var editor = sharedPreference.edit()
editor.putString("username", "Anupam")
editor.putLong("l", 100L)
editor.commit()

For retrieving a value:

sharedPreference.getString("username", "defaultName")
sharedPreference.getLong("l", 1L)

Kotlin code for deleting and removing SharedPreferences records

We can also clear all values or remove a specific value by calling clear() and remove(String key) methods.

editor.clear()
editor.remove("username")

Note: Changes to the editor after commit or apply are not considered.

Kotlin Android SharedPreferences Project Structure

In this application, we have a login screen that allows us to save/delete form data.

1. Layout Code

The code for the activity_main.xml layout file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/inUserId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:hint="User ID"
        android:inputType="number" />

    <EditText
        android:id="@+id/inPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/inUserId"
        android:hint="Password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/inPassword"
        android:text="SAVE USER DATA" />

    <Button
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/btnSave"
        android:text="CLEAR USER DATA" />

    <Button
        android:id="@+id/btnShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/inPassword"
        android:text="SHOW" />

    <Button
        android:id="@+id/btnShowDefault"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/btnSave"
        android:text="Show Default" />

</RelativeLayout>

2. MainActivity Kotlin Code

The code for the MainActivity.kt Kotlin class:

package com.journaldev.androidlysharedpreferences

import android.content.Context
import android.content.SharedPreferences
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.preference.PreferenceManager
import android.view.View
import com.journaldev.androidlysharedpreferences.PreferenceHelper.defaultPreference
import com.journaldev.androidlysharedpreferences.PreferenceHelper.password
import com.journaldev.androidlysharedpreferences.PreferenceHelper.userId
import com.journaldev.androidlysharedpreferences.PreferenceHelper.clearValues
import com.journaldev.androidlysharedpreferences.PreferenceHelper.customPreference

import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), View.OnClickListener {

    val CUSTOM_PREF_NAME = "User_data"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btnSave.setOnClickListener(this)
        btnClear.setOnClickListener(this)
        btnShow.setOnClickListener(this)
        btnShowDefault.setOnClickListener(this)

    }

    override fun onClick(v: View?) {
        val prefs = customPreference(this, CUSTOM_PREF_NAME)
        when (v?.id) {
            R.id.btnSave -> {
                prefs.password = inPassword.text.toString()
                prefs.userId = inUserId.text.toString().toInt()
            }
            R.id.btnClear -> {
                prefs.clearValues
            }
            R.id.btnShow -> {
                inUserId.setText(prefs.userId.toString())
                inPassword.setText(prefs.password)
            }
            R.id.btnShowDefault -> {
                val defaultPrefs = defaultPreference(this)
                inUserId.setText(defaultPrefs.userId.toString())
                inPassword.setText(defaultPrefs.password)
            }
        }
    }
}

object PreferenceHelper {

    val USER_ID = "USER_ID"
    val USER_PASSWORD = "PASSWORD"

    fun defaultPreference(context: Context): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)

    fun customPreference(context: Context, name: String): SharedPreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE)

    inline fun SharedPreferences.editMe(operation: (SharedPreferences.Editor) -> Unit) {
        val editMe = edit()
        operation(editMe)
        editMe.apply()
    }

    var SharedPreferences.userId
        get() = getInt(USER_ID, 0)
        set(value) {
            editMe {
                it.putInt(USER_ID, value)
            }
        }

    var SharedPreferences.password
        get() = getString(USER_PASSWORD, "")
        set(value) {
            editMe {
                it.putString(USER_PASSWORD, value)
            }
        }

    var SharedPreferences.clearValues
        get() = { }
        set(value) {
            editMe {
                it.clear()
            }
        }
}

Conclusion

Kotlin has simplified SharedPreferences management in Android applications and made the code more readable. By using Kotlin properties and higher-order functions, we can easily store, retrieve, and edit data. Integrating SharedPreferences into a Kotlin-based Android application offers an elegant and efficient way to manage user data locally. With Kotlin, developing Android apps is not only more efficient but also more enjoyable.

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: