Android SharedPreferences in Kotlin

Sagar Chapagain
ISOP Nepal
Published in
2 min readJul 6, 2019

In Android, SharedPrefences had always been favorite to store small data but sometimes big too, in a JSON string format.

Today I am going to simplify the data storing and retrieving method via
SharedPreferences in Kotlin way.

Let's start by observing some examples to store/retrieve data from shared preferences.

// get stored value
val myString = prefs.myString
// store value
prefs.myString = "My String Value"
// get stored array
val myStringArray = prefs.myStringArray
// store array
prefs.myStringArray = arrayOf("String 1","String 2","String 3")
// store value
prefs.myObject = MyObject("hello")
// retrieve my object
val myObject : MyObject? = prefs.myObject

First, we need to create a class Prefs with context as the constructor parameter.

class Prefs(context: Context) {

companion object {
private const val PREFS_FILENAME = "shared_prefs_name"

private const val KEY_MY_STRING = "my_string"
private const val KEY_MY_BOOLEAN = "my_boolean"
private const val KEY_MY_ARRAY = "string_array"
private const val KEY_MY_OBJECT = "my_object"
}
private val gson = Gson() private val sharedPrefs: SharedPreferences =
context.getSharedPreferences(PREFS_FILENAME, Context.MODE_PRIVATE)

var myString: String
get() = sharedPrefs.getString(KEY_MY_STRING, "") ?: ""
set(value) = sharedPrefs.edit { putString(KEY_MY_STRING, value) }

var myBoolean: Boolean
get() = sharedPrefs.getBoolean(KEY_MY_BOOLEAN, false)
set(value) = sharedPrefs.edit { putBoolean(KEY_MY_BOOLEAN, value) }
var myStringArray: Array<String>
get() = sharedPrefs.getStringSet(KEY_MY_ARRAY, emptySet())?.toTypedArray()?: emptyArray()
set(value) = sharedPrefs.edit { putStringSet(KEY_MY_ARRAY, value.toSet()) }
var myObject: MyObject?
get() {
val jsonString = sharedPrefs.getString(KEY_USER_DATA, null) ?: return null
return gson.fromJson(jsonString, object : TypeToken<MyObject>() {}.type)
}
set(value) = sharedPrefs.edit { putString(KEY_MY_OBJECT, gson.toJson(value)) }
}data class MyObject(val name: String)

Here, `sharedPrefs.edit{…}` is provided by the android core ktx library and should be implemented by adding core ktx dependency in appliation level `build.gradle`.
implementation “androidx.core:core-ktx:1.0.2”
and for Gson
implementation “com.google.code.gson:gson:2.8.5”

We can get the instance of `SharedPreferences` by using code:

val prefs = Prefs(context)

Furthermore, you can create the Singleton object of Prefs and use from anywhere within the app.

val prefs: Prefs by lazy {
Prefs(App.instance)
}

where App extends Application and should be included in AndroidManifest.

//App.kt
class App : Application() {
companion object {
lateinit var instance: App
}

override fun onCreate() {
super.onCreate()
instance = this
}
}
//AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest .....

<application
android:name=".App"
....
</application>
</manifest>

--

--