Android SharedPreferences Example | Kotlin

Hey, guys! In this article, we will familiarize ourselves with the best practices of SharedPreferences on Android(Kotlin). I’ll show you how to store and retrieve values in SharedPreferences. For better understanding, I will make an example of SharedPreferences android (application example) and take an example of writing and reading values in SharedPreferences. Then let’s get started.

What are SharePreferences?

SharedPreferences is an Android API that stores application data using key-value pairs and provides simple methods to read and write this data.

The Android system offers several ways to store data. These options are application-specific memory, shared memory, settings, and databases. SharePreference is coming to Preference. It provides a framework for storing private and primitive data in key-value pairs.

Why do I need SharePreferences?

They are mainly used to store the status of users with regard to their preferences, or to store small information (user data, etc.) without having to ask for permission. Naar mijn mening moet u kleine primitieve waarden in de voorkeuren opslaan, bijvoorbeeld B. Booleaanse waarden, Inks, Longs, Floats en Strings.

Method of preferential distribution

The general parameters have different MODEs, which are listed below.

1. Creating an Android application

Let’s take an example, let’s open an Android studio and create a new project. Now create an interface called IPreferenceHelper. In this interface, we define sets of getter to store or retrieve authorization values such as ApiKey, UserId, etc.

an example of sharing the com.sharedpreferencesexpletion package

Interface IPreferenceHelper {

A NICE SECURITY DETAIL.

for fun: 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 a value at the application level, so the SharedPreferences instance should be removed from the application once. He must be a loner. Create a class named PreferenceManager and implement IPreferenceHelper. As below.

open the class PreferencesManager constructor(context: context) : IPreferenceHelper {
private val PREFS_NAME = SharedPreferenceDemo
private var preference : General Conferences

init {
preferences = context.getSharedPreferences(PREFS_NAME, Context.PRIVATE_MODE)
}

overriding fun setApiKey(apiKey : String) {
preferences [API_KEY] = apiKey
}

cancel the fun of getApiKey() : String [
returns [API_KEY] preference ? :
}

overriding fun setUserId(userId : String) {
preferences [USER_ID] = userId
}

cancel the fun of getUserId() : String [
gives the [USER_ID] preference ? :
}

override fun override clearPrefs() {
preferences.edit().clear().apply()
}

companion object {
const val API_KEY = api_key
const val USER_ID = user_id
}
}

3. Write in your general parameters

Normally it is easy to write to SharedPreferences. But I am going to write a Kotlin extension, this extension makes writing very easy and shortens the model code.

/**
* SharedPreferences extension function to listen for fun edit() calls and apply()
* to any SharedPreferences operation.
*/
private threaded fun SharedPreferences.edit(operation) : (SharedPreferences.Editor) -> Unit) {
val editor = this.edit()
operation(editor)
editor.apply()
}

/**
* defines the key-value pair in SharedPreferences if it does not exist, otherwise it works the value on 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 general parameters

Reading a SharedPreferences value is also easy. I’m going to write another useful extension that allows to better control the retrieval of values in SharedPreferences. Check the following code

/**
* Finds the value on 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 ? {
returns when (T::class) {
String::class -> getString(key, defaultValue if ? String) if 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 ?
otherwise -> throw UnsupportedOperationException(Not yet implemented)
}
}

5. Finally, your PreferencesManager class looks like this

an example of sharing the com.sharedpreferencesexpletion package

import android.content.context
import android.content.SharedPreferences

open the class PreferencesManager constructor(context: context) : IPreferenceHelper {
private val PREFS_NAME = SharedPreferenceDemo
private var preference : General Conferences

init {
preferences = context.getSharedPreferences(PREFS_NAME, Context.PRIVATE_MODE)
}

overriding fun setApiKey(apiKey : String) {
preferences [API_KEY] = apiKey
}

cancel the fun of getApiKey() : String [
returns [API_KEY] preference ? :
}

overriding fun setUserId(userId : String) {
preferences [USER_ID] = userId
}

cancel the fun of getUserId() : String [
gives the [USER_ID] preference ? :
}

override fun override 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 fun edit() calls and apply()
* to any SharedPreferences operation.
*/
private threaded fun SharedPreferences.edit(operation) : (SharedPreferences.Editor) -> Unit) {
val editor = this.edit()
operation(editor)
editor.apply()
}

/**
* defines the key-value pair in SharedPreferences if it doesn’t exist, otherwise it works the value on 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 on 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 ? {
returns when (T::class) {
String::class -> getString(key, defaultValue if ? String) if 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 ?
otherwise -> throw UnsupportedOperationException(Not yet implemented)
}
}

6. Managing access rights in presentation layers

Yes, your PreferencesManager class is now ready for use. You can initialize the PreferencesManager class in ViewModel and Activity/Fragment, make sure the context must be applicationContext.

7. Now open active_main.xml and paste the code below.

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

 

 

 

 

 

8. Access the PreferencesManager class in your source file

Let’s take a look at the following code, so you can easily read and write the value in SharePreferences

an example of sharing the com.sharedpreferencesexpletion package

import android.annotation.suppressLint
import android.os.Bundle
import androidx.appcompat.appCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

Main activity class : AppCompatActivity() {.

Private Val Preferance Helper: IPreferenceHelper the lazy { PreferencesManager(applicationContext)}

@SuppressLint(SetTextI18n)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// display recorded 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())
// show 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 for this EditText and click on the button. The value is displayed in the TextView. So you can read and write a small amount of data in key-value pairs!

Conclusion

In this example of SharedPreferences android, we will learn how to store and retrieve a value in SharedPreferences. I try to follow the best practices of Android development. Yet you want to improve… Welcome, welcome, welcome…

Follow this article to detect network changes in Android!

Related Tags:

kotlin sharedpreferences helperkotlin sharedpreferences stackoverflowhow to get data from shared preference in androidandroid sharedpreferences listview tutorialshared preference login example in androidwhere are shared preferences stored androidandroid login with database using shared preferencesandroid login and registration using sharedpreferences

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *