SharedPreferences is a powerful Android class that allows a group of settings to be shared amongst apps, and provides a unified API for developers to access and modify the settings. This tutorial will show you how to use SharedPreferences to store and retrieve a simple list of settings to use in your own application.

Android has a SharedPreferences class which basically allows you to save and retrieve arbitrary values across multiple applications or activities. But the real power of SharedPreferences comes from a concept known as scoping. Basically, this allows us to create different “preferences” depending on the Android Application or Activity which is currently “in scope”.

Hello, my friends! In this article, we will explore the best practices for using SharedPreferences in Android(Kotlin). I’ll show you how to store and retrieve values in SharedPreferences. To understand it better, I will create an example SharedPreferences for Android (example app) and look at an example of writing and reading values in SharedPreferences. So let’s get started.

What are the sharing preferences?

SharedPreferences is an Android API that stores application data using key-value pairs and provides simple methods to read and write that data. The Android system offers you several ways to store your data. These are the following options: Application-specific memory, shared memory, presets, databases. SharePreferences is a part of Preference. It provides a framework for storing private and primitive data in key-value pairs.

Why SharePreferences?

They are mainly used to store user status when it comes to user settings, or to store small pieces of information (user data, etc.) without requiring storage authorization. In my opinion, small primitive values like booleans, ints, longs, floats and strings should be stored in preferences.

Modes in SharePreferences

SharedPreferences has several MODES, which are listed below word-image-3078

1. Creating an application for android

Let’s take an example, open android studio and create a new project. Now create an interface called IPreferenceHelper. In this interface, we define some getter/setters to store or retrieve parameter values such as ApiKey and UserId, etc. an example of the package com.sharedpreferencesexpletion Interface IPreferenceHelper { fun setApiKey(apiKey : String) fun getApiKey() : The line is fun setUserId(userId : String) fun getUserId() : The line is fun clearPrefs() }

2. Create a class with one button to control parameters

Ideally, SharedPreferences stores values at the application level, so the SharedPreferences instance should be a single instance for the entire application. It should be a singleton. Create a singleton class called PreferenceManager and implement IPreferenceHelper. As below. open the PreferenceManager constructor(context : Context) class: IPreferenceHelper { private val PREFS_NAME = SharedPreferenceDemo private var preferences : General Conferences init { preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) } override fun setApiKey(apiKey : String) { preferences[API_KEY] = apiKey } override fun getApiKey() : String { return preferences[API_KEY] ? : } override fun setUserId(userId : String) { preferences[USER_ID] = userId } override fun getUserId() : String { return preferences[USER_ID] ? : } override fun clearPrefs() { preferences.edit().clear().apply() } companion object { const val API_KEY = api_key const val USER_ID = user_id } }

3. Writing to general parameters

Normally, the entry in SharedPreferences is simple. But I will write a Kotlin extension, this extension makes writing very easy and shortens the template code. /** * SharedPreferences extension function to listen for edit() and apply() calls * on any SharedPreferences operation. */ private inline fun SharedPreferences.edit(operation : (SharedPreferences.Editor) -> Unit) { val editor = this.edit() operation(editor) editor.apply() } /** * Set the key-value pair in shared preferences if it does not exist, otherwise update the value with this [key] */ private operator fun SharedPreferences.set(key : String, value : Any ?) { when (value) { is String ? -> edit { it.putString(key, value) } is Int -> edit { it.putInt(key, value) } is Boolean -> edit { it.putBoolean(key, value) } is Float -> edit { it.putFloat(key, value) } is Long -> edit { it.putLong(key, value) } else -> throw UnsupportedOperationException(Not yet implemented) } }

4.  Reading Shared Preferences

Reading a value in SharedPreferences is also easy. I will write another useful extension that gives more control over retrieving SharedPreferences values. Check the following code /** * Finds the value with the specified key. * [T] – value type * @param defaultValue optional default value – takes null for strings, false for bools, and -1 for numeric values if [defaultValue] is not specified */ private inline operator fun SharedPreferences.get( key : String, defaultValue : T ? = null ) T ? { return when (T::class) { String::class -> getString(key, defaultValue as ? String) as T ? Int::class -> getInt(key, defaultValue if ? Int ? : -1) if T ? Boolean::class -> getBoolean(key, defaultValue if ? Boolean ? : false) if T ? Float::class -> getFloat(key, defaultValue if ? Float ? : -1f) if T ? Long::class -> getLong(key, defaultValue if ? Long ? : -1) if T ?else -> throw UnsupportedOperationException(Not yet implemented)}

5. Finally, your PreferenceManager class looks like this

example of shared preferences import android.content.Context import android.content.SharedPreferences open the PreferenceManager constructor(context : Context) class: IPreferenceHelper { private val PREFS_NAME = SharedPreferenceDemo private var preference : Shared Preferences init { preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) } override fun setApiKey(apiKey : String) { preferences[API_KEY] = apiKey } Cancel the getApiKey() function: String { return preferences[API_KEY] ? : } override fun setUserId(userId : String) { preferences[USER_ID] = userId } override fun getUserId() : String { return preferences[USER_ID] ? : } override fun clearPrefs() { preferences.edit().clear().apply() } companion object { const val API_KEY = api_key const val USER_ID = user_id } } /** * SharedPreferences extension function to listen for edit() and apply() fun calls * to each SharedPreferences operation. */ private threaded fun SharedPreferences.edit(operation) : (SharedPreferences.Editor) -> Unit) { val editor = this.edit() operation(editor) editor.apply() } /** * Set the key-value pair in SharedPreferences if it does not exist, otherwise update the value of this [key] */ private operator fun SharedPreferences.set(key : String, value : Any ?) { when (value) { is String ? -> edit { it.putString(key, value) } is Int -> edit { it.putInt(key, value) } is Boolean -> edit { it.putBoolean(key, value) } is Float -> edit { it.putFloat(key, value) } is Long -> edit { it.putLong(key, value) } else -> throw UnsupportedOperationException(Not yet implemented) } } /** * Finds the value with the specified key. * [T] – value type * @param defaultValue optional default value – takes null for strings, false for bools, and -1 for numeric values if [defaultValue] is not specified */ private inline operator fun SharedPreferences.get( key : String, defaultValue : T ? = null ) T ? { return when (T::class) { String::class -> getString(key, defaultValue as ? String) as T ? Int::class -> getInt(key, defaultValue if ? Int ? : -1) if T ? Boolean::class -> getBoolean(key, defaultValue if ? Boolean ? : false) if T ? Float::class -> getFloat(key, defaultValue if ? Float ? : -1f) if T ? Long::class -> getLong(key, defaultValue if ? Long ? : -1) if T ?else -> throw UnsupportedOperationException(Not yet implemented)}

6. Go to Preference Management under Presentation Layers

Yes, your PreferenceManager class is now ready to be used. You can initialize the PreferenceManager class in your ViewModel and Activity/Fragment, make sure the context is applicationContext.

7. Now open the file activity_main.xml and paste the code below.

To give an interesting example, I have added two edit texts and a button in this layout

8. Provide access to the PreferenceManager class in yoursource file.

Let’s look at the following code. This way you can easily read and write the value to SharePreferences. example of shared preferences import android.annotation.SuppressLint import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* Class MainActivity : AppCompatActivity() {. private trap preferenceHelper : IPreferenceHelper lazy { PreferencesManager(applicationContext) } @SuppressLint(SetTextI18n) override fun onCreate(savedInstanceState : Bundle ?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // display saved data textView.text = API key – > ${preferenceHelper.getApiKey()} n user id -> ${preferenceHelper.getUserId()} button.setOnClickListener { // update data in SharedPreference preferenceHelper.setApiKey(editText.text.toString()) preferenceHelper.setUserId(editText2.text.toString()) // display saved data textView.text = API Key – > ${preferenceHelper.getApiKey()} n User Id -> ${preferenceHelper.getUserId()} } } }

7. Construction and testing

Let the application run, in motion your application will run, Now enter some values of this EditText and click on the button. The value is displayed in the TextView. This way you can read and write small amounts of data in key-value pairs!

Output

In this android SharedPreferences example, we will learn how to store and retrieve values in SharedPreferences. I try to follow the best practices of Android development. Anyway, you want… The most welcoming Follow this article to detect network changes in Android!

Frequently Asked Questions

What is SharedPreferences in Android with example?

SharedPreferences is a key feature of Android, and it lends its name to the android/data/shared_preferences.xml file. The file contains details about the app’s preferences and is used for various purposes. For instance, when the app is run, the shared_preferences.xml file is loaded from the SD card, and then the app provides the data in the file to the OS and the OS saves it to the data storage. SharedPreferences is a powerful and flexible storage system in Android. It’s a good way to store application settings without having to implement your own DatabaseManager. It supports multi-user support, and is a good place to put user preferences that need to be persisted across device and application upgrades.

What is the use of SharedPreferences in Android?

SharedPreferences are powerful and flexible. They have been introduced in Android SDK version 4.3. However, they do not require any new APIs in order to use the SharedPreferences. SharedPreferences can be used in conjunction with the SharedPreferences annotation. SharedPreferences also provides the API to store the key-value pair in SharedPreferences. SharedPreferences are powerful tools for storing application settings that can be used across multiple applications. The typical problem that developers encounter with SharedPreferences is that they cannot change the SharedPreferences object. This can be a problem if the SharedPreferences value is important to the app or if it needs to be shared across applications. This post is to show how to change the SharedPreferences value in an Android application.

How do I use Kotlin SharedPreferences?

SharedPreferences are a great way to store information in the background of an Android app but there is still a lot left to be desired. They are still very much a work in progress. If you want to see all the ways to use shared preferences there are some great articles on the internet. Kotlin shared preferences work as you would expect, but they also have a few extra features which I will highlight. SharedPreferences is a great way to store preferences, such as WiFi passwords, bookmarks, contacts, and more. In this post, you will learn how to use SharedPreferences and you will also see the Kotlin plugin that was created by the author of this blog post.

kotlin sharedpreferences helperget sharedpreferences in androidkotlin sharedpreferences stackoverflowsharedpreferences stores the data in which formatget value from sharedpreferences in androidhow to store multiple values in sharedpreferences in android,People also search for,Feedback,Privacy settings,How Search works,kotlin sharedpreferences helper,get value from sharedpreferences in android,how to store multiple values in sharedpreferences in android,shared preference login example in android,get sharedpreferences in android,kotlin sharedpreferences stackoverflow,shared preferences in android kotlin stackoverflow,sharedpreferences stores the data in which format

You May Also Like

How to use your Smartphone as Android TV Remote wirelessly [Guide]

If you forget to keep the remote next to you during binge…

How to Power Off & Restart Samsung Galaxy S21, S21+ and S21 Ultra

Samsung has finally released the flagship of its 2021 smartphone series –…

Samsung Chromebook 4 Review (2021 XE310XBA-KC1US model)

Samsung has unveiled a new Chromebook 2021, the Chromebook 4 XE310XBA-KC1US. This…

PDFBear: The Best Tool To Easily Merge Your Files For Free

Before the pandemic hit several countries and paralyzed our movements, many people…