Skip to content

Instantly share code, notes, and snippets.

@malwinder-s
Last active May 24, 2020 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malwinder-s/bf2292bcdda73d7076fc080c03724e8a to your computer and use it in GitHub Desktop.
Save malwinder-s/bf2292bcdda73d7076fc080c03724e8a to your computer and use it in GitHub Desktop.
Saving object of the model class in Preferences
package com.malwinder.kotlindemo.preference
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import com.google.gson.GsonBuilder
/**
* Singleton class for managing preferences for POJO or model class's object.
* @author Malwinder Singh
* medium.com/@dev.malwinder
*/
object ModelPreferencesManager {
//Shared Preference field used to save and retrieve JSON string
lateinit var preferences: SharedPreferences
//Name of Shared Preference file
private const val PREFERENCES_FILE_NAME = "PREFERENCES_FILE_NAME"
/**
* Call this first before retrieving or saving object.
*
* @param application Instance of application class
*/
fun with(application: Application) {
preferences = application.getSharedPreferences(
PREFERENCES_FILE_NAME, Context.MODE_PRIVATE)
}
/**
* Saves object into the Preferences.
*
* @param `object` Object of model class (of type [T]) to save
* @param key Key with which Shared preferences to
**/
fun <T> put(`object`: T, key: String) {
//Convert object to JSON String.
val jsonString = GsonBuilder().create().toJson(`object`)
//Save that String in SharedPreferences
preferences.edit().putString(key, jsonString).apply()
}
/**
* Used to retrieve object from the Preferences.
*
* @param key Shared Preference key with which object was saved.
**/
inline fun <reified T> get(key: String): T? {
//We read JSON String which was saved.
val value = preferences.getString(key, null)
//JSON String was found which means object can be read.
//We convert this JSON String to model object. Parameter "c" (of
//type Class < T >" is used to cast.
return GsonBuilder().create().fromJson(value, T::class.java)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment