Skip to content

EdwarDDay/serialization.kprefs

Repository files navigation

Android SharedPreferences serialization

REUSE status Develop Maven Central

Preferences serialization is a kotlinx.serialization format to serialize arbitrary objects in androids SharedPreferences.

The documentation can be found on the projects Github Page.

Contents

Small Example

@Serializable
data class Person(val name: String, val age: Int, val children: List<Person> = emptyList())

val preferences = Preferences(sharedPreferences)

val abby = Person("Abby", 12)
val bob = Person("Bob", 10)
val charles = Person("Charles", 36, listOf(abby, bob))

preferences.encode("person", charles)
// ...
val person: Person = preferences.decode("person")
assertEquals(charles, person)

You can get the full code here.

Delegated Properties Example

val preferences = Preferences(sharedPreferences)

var someFlag: Boolean by preferences.asProperty(default = false)

fun someComputation() {
    someFlag = true
}

someComputation()
if (!someFlag) { // reads value from SharedPreferences at key "someFlag"
    fail()
}

You can get the full code here.

Setup

You need to apply the kotlinx.serialization plugin and add this library as dependency.

Kotlin DSL:

plugins {
    kotlin("plugin.serialization") version "2.0.20"
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("net.edwardday.serialization:kprefs:0.13.0")
}

Note: additional information to the serialization plugin can be found in the kotlinx.serialization repository.

Features

  • support for all primitive types
    • support for double by encoding it to
      • Float - with loss of precision
      • String - with the string representation
      • Long - with the bits representation
  • support nullability (stored in extra field)
  • support for native Set<String> encoding
  • support for encoding classes
  • support for sealed classes
  • support for objects by encoding an object start with a Boolean
  • support for property delegated properties
  • support for synchronization (synchronize on every object read / write)

Building

To build the library just run ./gradlew library:build. To publish it to you local maven repository use ./gradlew library:publishToMavenLocal