Adapter library for SharedPreferences

Related tags

Kotlin EasyPrefs
Overview

EasyPrefs

Adapter library for SharedPreferences which reduces boilerplate needed to store simple data, but open enough to not interfere with your own logic.

Quick preview

Lets see the example usage of SharedPreferences:

class MyPreferences(private val preferences: SharedPreferences) {
   
   var myString: String
        get() = preferences.getString(MY_KEY, null) ?: MY_DEFAULT_VALUE
        set(value) {
            prefs.edit(commit = true) { 
                putString(MY_KEY, value)
            }
        }
    
    companion object {
        const val MY_KEY = "my_key"
        const val MY_DEFAULT_VALUE = "default"
    }
}

We can see a lot of boilerplate code, also if you would want to add another property you need to create another field with getter and setter, add key and default value to companion object. And here EasyPrefs comes to the rescue! What if we would be able to declare your SharedPreferences property like this:

class MyPreferences(private val preferences: SharedPreferences) : EasyPrefs(preferences) {
    
    var myString by string(commit = true, default = MY_DEFAULT_VALUE)
    
    companion object {
        const val MY_DEFAULT_VALUE = "default"
    }
}

We got rid of repetitive boilerplate code, brilliant! But there is more. EasyPrefs makes it easy to observe value changes with use of Kotlin Flow, just implement EasyPrefsFlow and use flow delegates:

class MyPreferences(private val preferences: SharedPreferences) : EasyPrefsFlow(preferences) {
    
    var myString by string(commit = true, default = MY_DEFAULT_VALUE)
    // key is the property you want to observe
    val myStringFlow by stringFlow(key = ::myString)
    ...
}

EasyPrefs also makes it easy to use custom property types that are not supported by SharedPreferences. Just create implementation of TypeAdapter that will convert your objects into nullable string values and then recreate them when needed. It also supports Flow delegates!

class ByteArrayAdapter : TypeAdapter<ByteArray?> {
    override fun toString(value: ByteArray?): String? =
        value?.let { Base64.encodeToString(it, Base64.NO_WRAP) }

    override fun fromString(value: String?): ByteArray? =
        value?.let { Base64.decode(it, Base64.NO_WRAP) }
}
class MyPreferences(
    private val preferences: SharedPreferences,
    byteArrayAdapter: TypeAdapter<ByteArray?>,
) : EasyPrefsFlow(preferences) {
    var someData: ByteArray? by custom(commit = true, adapter = byteArrayAdapter)
    val someDataFlow: Flow<ByteArray?> by customFlow(key = ::someData, adapter = byteArrayAdapter)
}

Keys

But now the great question arises. What about the keys to actual SharedPreferences implementation? It couldn't just disappear! 🤔

The keys are generated with use of Kotlin Reflect. This is the formula under the hood:

fun getKeyFor(thisRef: EasyPrefs, property: KProperty<*>): String =
    "${thisRef::class.qualifiedName}_${property.name}"

So the library just generates the key for example like this: "com.example.app.data.prefs.Preferences_myString". This way we don't need to create them ourselves, and we don't need to make sure that every key is unique manually! If you want to obtain this key for your property you can do so with use of getKeyFor(KProperty<*>) function in EasyPrefs abstraction. The only downside of this solution is that to create a Flow for property, the Flow delegate needs to be used within the same class.

Setup

The library is avaliable on Maven repository, just add mavenCentral() to your project and this dependency:

implementation "io.github.buszi0809:easyprefs:1.0.0"

Then extend EasyPrefs or EasyPrefsFlow in object that handles your SharedPreferences and you're easy to go. 😄

Feedback

The library is created and maintained by a single unit, a passionate Android Developer that had seen the field for improvements within SharedPreferences component. If you have any ideas or feedback - please feel free to use Discussions tab of this Repo!

You might also like...
Don't write a RecyclerView adapter again. Not even a ViewHolder!

LastAdapter Don't write a RecyclerView adapter again. Not even a ViewHolder! Based on Android Data Binding Written in Kotlin No need to write the adap

The Android maps adapter
The Android maps adapter

MapMe MapMe is an Android library for working with Maps. MapMe brings the adapter pattern to Maps, simplifying the management of markers and annotatio

YouTube Player library for Android and Chromecast, stable and customizable.
YouTube Player library for Android and Chromecast, stable and customizable.

android-youtube-player android-youtube-player is a stable and customizable open source YouTube player for Android. It provides a simple View that can

A highly customizable calendar library for Android, powered by RecyclerView.
A highly customizable calendar library for Android, powered by RecyclerView.

CalendarView A highly customizable calendar library for Android, powered by RecyclerView. With this library, your calendar will look however you want

View
View "injection" library for Android.

Kotter Knife Deprecated: This was a terrible idea because it allocates an object for every view reference. Do not use, and do not use anything like it

Android library that creates app shortcuts from annotations
Android library that creates app shortcuts from annotations

Shortbread Android library that generates app shortcuts for activities and methods annotated with @Shortcut. No need to touch the manifest, create XML

Kotlin library for Android
Kotlin library for Android

KAndroid Kotlin library for Android providing useful extensions to eliminate boilerplate code in Android SDK and focus on productivity. Download Downl

A Kotlin DSL wrapper around the mikepenz/MaterialDrawer library.
A Kotlin DSL wrapper around the mikepenz/MaterialDrawer library.

MaterialDrawerKt Create navigation drawers in your Activities and Fragments without having to write any XML, in pure Kotlin code, with access to all t

Events Calendar is a user-friendly library that helps you achieve a cool Calendar UI with events mapping. You can customise every pixel of the calendar as per your wish and still achieve in implementing all the functionalities of the native android calendar in addition with adding dots to the calendar which represents the presence of an event on the respective dates. It can be done easily, you are just a few steps away from implementing your own badass looking Calendar for your very own project!
Releases(1.1.0)
  • 1.1.0(Nov 15, 2021)

    Changelog:

    Features:

    • RxJava3 support! - use EasyPrefsRx to use property observable delegates
    • For nullable values added Nullable wrapper to support RxJava (RxJava data streams don't accept nullable values), use Observable<Nullable<T>>.mapOptional() extension to remove wrapper (requires minSdk >= 24)

    Adjustments:

    • Set minSdk required to use the library to 1
    • Moved delegates to be protected functions of abstractions, delegates won't be accessible globally
    • Added non-nullable variants for String and Set<String> data flows
    • Added default values to custom type delegates
    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Oct 17, 2021)

Owner
Kacper Wojciechowski
Android Developer at Netguru
Kacper Wojciechowski
A Kotlin library for reactive and boilerplate-free SharedPreferences in Android

KPreferences A Kotlin library for reactive and boilerplate-free Shared Preferences in Android. With KPreferences you can use Kotlin's marvelous delega

Mohamad Amin Mohamadi 19 Dec 16, 2020
The most complete and powerful data-binding library and persistence infra for Kotlin 1.3, Android & Splitties Views DSL, JavaFX & TornadoFX, JSON, JDBC & SQLite, SharedPreferences.

Lychee (ex. reactive-properties) Lychee is a library to rule all the data. ToC Approach to declaring data Properties Other data-binding libraries Prop

Mike 112 Dec 9, 2022
Easy lightweight SharedPreferences library for Android in Kotlin using delegated properties

Easy lightweight SharedPreferences library for Android in Kotlin using delegated properties Idea Delegated properties in Kotlin allow you to execute a

null 25 Dec 27, 2022
Android Library to make SharedPreferences usage easier.

KotlinPreferences Kotlin Android Library, that makes preference usage simple and fun. KotlinPreferences now have a brother. With KotlinPreferences, yo

Marcin Moskała 50 Nov 6, 2022
Kotpref - Android SharedPreferences delegation library for Kotlin

Kotpref Android SharedPreference delegation for Kotlin. Install repositories { mavenCentral() } dependencies { // core implementation 'co

Takao Chiba 684 Dec 22, 2022
Android SharedPreferences Helper

PocketDB Android SharedPreferences Helper This is SharedPreferences Helper like a database noSql. Support AES encryption Latest Version Download depen

Muhammad Utsman 9 Jun 20, 2021
RecyclerView Adapter Library with different models and different layouts as convenient as possible.

RecyclerView Presenter Convenience library to handle different view types with different presenters in a single RecyclerView. How to install repositor

Jan Rabe 86 Dec 26, 2022
A simple and easy adapter for RecyclerView. You don't have to make adapters and view holders anymore. Slush will help you.

한국어 No more boilerplate adapters and view holders. Slush will make using RecyclerView easy and fast. The goal of this project is to make RecyclerView,

SeungHyun 26 Sep 13, 2022
Android RecyclerView Adapter with nested items & expand/contract functionality

AccordionRecycler Android RecyclerView Adapter with nested items & expand/contract functionality With AccordionRecycler you can easily create awesome

Fanis Veizis 17 Aug 18, 2022
💡🚀⭐️ A generalized adapter for RecyclerView on Android which makes it easy to add heterogeneous items to a list

Mystique is a Kotlin library for Android’s RecyclerView which allows you to create homogeneous and heterogeneous lists effortlessly using an universal

Rahul Chowdhury 48 Oct 3, 2022