Skip to content

Instantly share code, notes, and snippets.

@oakkub
Created October 30, 2017 06:47
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 oakkub/c810e633f9e0ea09e8e155c2333886d6 to your computer and use it in GitHub Desktop.
Save oakkub/c810e633f9e0ea09e8e155c2333886d6 to your computer and use it in GitHub Desktop.
import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
/**
* Created by oakkub on 10/18/2017 AD.
*/
object PreferenceHelper {
private const val prefsName = "trueyou_edc_prefs"
lateinit var prefs: SharedPreferences
lateinit var gson: Gson
fun init(context: Context, gson: Gson) {
this.prefs = context.applicationContext.getSharedPreferences(prefsName, Context.MODE_PRIVATE)
this.gson = gson
}
fun putString(key: String, value: String) {
checkValidPrefsKey(key)
prefs.edit().putString(key, value).apply()
}
fun putInt(key: String, value: Int) {
checkValidPrefsKey(key)
prefs.edit().putInt(key, value).apply()
}
fun putBoolean(key: String, value: Boolean) {
checkValidPrefsKey(key)
prefs.edit().putBoolean(key, value).apply()
}
fun putFloat(key: String, value: Float) {
checkValidPrefsKey(key)
prefs.edit().putFloat(key, value).apply()
}
fun putLong(key: String, value: Long) {
checkValidPrefsKey(key)
prefs.edit().putLong(key, value).apply()
}
fun <E> putObject(key: String, value: E) {
checkValidPrefsKey(key)
val jsonData = gson.toJson(value)
prefs.edit().putString(key, jsonData).apply()
}
fun getString(key: String, defValue: String): String {
checkValidPrefsKey(key)
return prefs.getString(key, defValue)
}
fun getInt(key: String, defValue: Int): Int {
checkValidPrefsKey(key)
return prefs.getInt(key, defValue)
}
fun getBoolean(key: String, defValue: Boolean): Boolean {
checkValidPrefsKey(key)
return prefs.getBoolean(key, defValue)
}
fun getFloat(key: String, defValue: Float): Float {
checkValidPrefsKey(key)
return prefs.getFloat(key, defValue)
}
fun getLong(key: String, defValue: Long): Long {
checkValidPrefsKey(key)
return prefs.getLong(key, defValue)
}
inline fun <reified E> getObject(key: String): E? {
val dataJson = prefs.getString(key, null) ?: return null
return gson.fromJson(dataJson, object: TypeToken<E>() {}.type)
}
operator fun contains(key: String): Boolean {
checkValidPrefsKey(key)
return prefs.contains(key)
}
fun remove(key: String) {
checkValidPrefsKey(key)
prefs.edit().remove(key).apply()
}
fun clear() {
prefs.edit().clear().apply()
}
fun checkValidPrefsKey(key: String) {
require(!key.isBlank()) {
throw IllegalArgumentException("Preferences key must not empty")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment