mathcamp by fiberglass

Easy lightweight SharedPreferences library for Android in Kotlin using delegated properties


Idea

Delegated properties in Kotlin allow you to execute arbitrary code whenever a field is accessed. The cool thing about delegated properties is that we can package up the code and reuse it.

Let’s package up the notion of getting from SharedPreferences and writing to SharedPreferences.

Usage

Just stick metadata in your classes with specific delegated properties

class User(val ctx: Context) {
  companion object {
    private val namespace = "user"
  }

  var email by StringSavable(namespace, ctx)
  var lastSaved by DateSavable(namespace, ctx)
  var phone by LongSavable(namespace, ctx)
}

Get and set just like normal field properties

val u = User(this)
/* ... */

// Get
val greetings = "Hello ${u.name}"

/* ... */

// Set
u.name = "Brandon"

If you want to save custom a custom data type, you just have to write-to and read-from SharedPreferences

private object DateGetterSetter {
  // make it a lazy object to reuse the same inner-class for each savable
  val dates by lazy {
    object: GetterSetter<Date> {
      override fun get(prefs: SharedPreferences, name: String): Date =
          Date(prefs.getLong(name, System.currentTimeMillis()))

      override fun put(edit: SharedPreferences.Editor, name: String, value: Date) {
        edit.putLong(name, value.time)
      }
    }
  }
}

fun DateSavable(namespace: String, ctx: Context): Savable<Date> =
    Savable(namespace, ctx, DateGetterSetter.dates)

Example App

See the app module for a sample app

fiberglass app icon

screenshot

Default values

Shared preferences requires default values when the data is missing. The default values for the builtin savables are:

Type Default Value
StringSavable ””
IntSavable Int.MIN_VALUE
LongSavable Long.MIN_VALUE
DoubleSavable Double.MIN_VALUE
FloatSavable Float.MIN_VALUE
BooleanSavable false
DateSavable Date now

Consistency

Savable field writes are eventually consistent (implemented with apply() on the shared preferences editor).

It would make sense to also support consistent writes (implemented with commit() on the shared preferences editor) somehow. Please send a PR or open an issue with ideas.

Related Libraries

materialdrawerkt

A Kotlin DSL wrapper around the mikepenz/MaterialDrawer library.

Last updated 3 mins ago

anvil

Minimal UI library for Android inspired by React

Last updated 3 mins ago

mapme

The Android maps adapter

Last updated 3 mins ago

bubble

Screen orientation detector for android

Last updated 3 mins ago

korui

Korui - Kotlin cORoutines User Interfaces - korio + kimage + korui for JVM, Android and HTML5

Last updated 3 mins ago