ObjectPreference

Additional

Language
Kotlin
Version
N/A
Created
Jan 8, 2020
Updated
Jan 30, 2020 (Retired)
Owner
Stamatis Stiliatis (Codeblin)
Contributor
Stamatis Stiliatis (Codeblin)
1
Activity
Badge
Generate
Download
Source code

Advertisement

ObjectPreference

Fast and easy Shared Preferences managing with object mapping annotations for simple or complex class structures

How to use

  • app build.gradle
implementation 'com.codeblin.annotations:ObjectPreferences:<latest-version>'
kapt 'com.codeblin.compiler:ObjectPreferencesCompiler:<latest-version>'

ObjectPreferences uses java 8 so you need to set compile options to target Java 8

android{
 compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }
}
  • First create you model and annotate with @Document Annotation

Example

@Document
data class User(
    val id: Int,
    val firstName: String,
    val lastName: String,
    val age: Int,
    val transactions: List<Transaction>
)

data class Transaction(
    val id: Int,
    val date: Date,
    val amount: Double
)
  • Build project. Now initialize SharedPrefManager at your Application class
SharedPrefManager.initialize(this)

This will generate the class you will be using which is the name of your class with the suffix 'StoreModel'

class UserStoreModel(
    private val value: User
) {
    fun save() {
        com.codeblin.objectpreference.SharedPrefManager.saveObject<User>(
            "User",
            value
        )
    }

    fun get(): User =
        com.codeblin.objectpreference.SharedPrefManager.getObject<User>(
            "User"
        )

    fun delete() {
        com.codeblin.objectpreference.SharedPrefManager.delete("User")
    }
}

That's it!

Features

Use <your-annotated-class-name>StoreModel class to operate

  • Save
val user = UserStoreModel(User(..))
user.save()
  • Get
user.get()
  • Delete
user.delete()
  • Create an instance with the default empty constructor to reuse your StoreModel across your app
user = UserStoreModel()
  • Clear all
SharedPrefManager.clear()