SharedPreferences is a great Android library. It allows us to store objects, such as preferences, in a shared space. SharedPreferences has support for many different object types, including strings, ints, floats, bytes, and booleans. It also supports the @SharedPreferences annotation, which lets us map a string key to a shared object. Most of the time, we will use the default constructor for our shared preferences.
Android SharedPreferences is an Android library that lets you store data that is synchronized across multiple activities. This can be useful for things like storing preferences on a user account to remember things like your Wi-Fi password or a list of contacts.
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 for reading and writing 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.
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.
SharedPreferences has several MODES, which are listed below
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. example of shared preferences 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 singleton class for preference management
Ideally, SharedPreferences stores values at the application level, so the SharedPreferences instance should be a single instance for the entire application. It must 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 : Shared Preferences 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 an extension for Kotlin. This improvement will simplify the writing process and reduce the amount of 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) } }
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 preferences : Shared Preferences 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 } } /** * 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) } } /** * 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 { PreferenceManager(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
Start the application, after some time your application will run, now enter some values in 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
Today we will learn what is SharedPreferences in android. SharedPreferences contains two key parts: value and key. Value is the content of SharedPreferences object and key is the unique identifier of the value. Values must be strings and can be any type of string e.g. java, json, int etc. If you are using apk file you can find values from file name like “android.widget.TextView”. We can also create a new SharedPreferences object from java code as SharedPreferences myPreferences = new SharedPreferences(context, “myPreferences”, “myKey”). share() SharedPreferences is a powerful Android feature which can be used to store a user-specific data (like passwords, storage space, photos, contacts, etc.) in memory. This means that the data is stored in the phone and is automatically available when needed. The same data is available to any corresponding application linked to the same SharedPreferences object.
SharedPreferences are a way to store data about an application, so that the data can be available across multiple apps. They can be a great way to store preferences, such as the languages you want to use, the time zone information you like to use, or the list of frequently used apps. SharedPreferences is a centralized system that stores and manages preferences for an Android application. Here’s how shared preferences work:
This is an example SharedPreferences file for Kotlin, an open source programming language for the Java virtual machine. This file is for SharedPreferences which help you store data in an Android application and retrieve it later. SharedPreferences is a powerful Android framework that simplifies the way applications can store and access data. In this tutorial, we’ll look at how to store and retrieve a list of Twitter users by their username.
Related Tags:
kotlin sharedpreferences stackoverflowget sharedpreferences in androidshared preferences in android kotlin stackoverflowkotlin sharedpreferences helperget 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 stackoverflow,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,sharedpreferences stores the data in which format,shared preferences in android kotlin stackoverflow,kotlin sharedpreferences helper