Skip to content

Instantly share code, notes, and snippets.

@BurakDizlek
Last active August 25, 2017 09:07
Show Gist options
  • Save BurakDizlek/3369c9734045d70c55c74954fc98abeb to your computer and use it in GitHub Desktop.
Save BurakDizlek/3369c9734045d70c55c74954fc98abeb to your computer and use it in GitHub Desktop.
SharedPreferences Helper Class
class Share private constructor() {
private var context: Context? = null
private var preferences: SharedPreferences? = null
companion object {
private val PREF_NAME = "_Share"
private val ourInstance: Share by lazy { setInstance() }
private fun setInstance(): Share {
val share = Share()
share.context = MyApplication.context
share.preferences = share.context!!.getSharedPreferences(PREF_NAME,
Activity.MODE_PRIVATE)
return share
}
fun put(key: String, `val`: String) {
val prefEdit = ourInstance.preferences!!.edit()
prefEdit.putString(key, `val`)
prefEdit.apply()
}
fun put(key: String, `val`: Boolean?) {
val prefEdit = ourInstance.preferences!!.edit()
prefEdit.putBoolean(key, `val`!!)
prefEdit.apply()
}
fun put(key: String, `val`: Int) {
val prefEdit = ourInstance.preferences!!.edit()
prefEdit.putInt(key, `val`)
prefEdit.apply()
}
fun put(key: String, `val`: Float?) {
val prefEdit = ourInstance.preferences!!.edit()
prefEdit.putFloat(key, `val`!!)
prefEdit.apply()
}
fun put(key: String, `val`: Long?) {
val prefEdit = ourInstance.preferences!!.edit()
prefEdit.putLong(key, `val`!!)
prefEdit.apply()
}
fun put(key: String, list: List<String>) {
val prefEdit = ourInstance.preferences!!.edit()
val gson = Gson()
val json = gson.toJson(list)
prefEdit.putString(key, json)
prefEdit.apply()
}
fun getStringList(key: String, defaultValue: String): List<String> {
val gson = Gson()
val json = ourInstance.preferences!!.getString(key, defaultValue)
val type = object : TypeToken<List<String>>() {
}.type
val list = gson.fromJson<List<String>>(json, type)
return list
}
fun getString(key: String, defaultValue: String): String {
return ourInstance.preferences!!.getString(key, defaultValue)
}
fun getBoolean(key: String, defaultValue: Boolean): Boolean {
return ourInstance.preferences!!.getBoolean(key, defaultValue)
}
fun getFloat(key: String, defaultValue: Float): Float {
return ourInstance.preferences!!.getFloat(key, defaultValue)
}
fun getInt(key: String, defaultValue: Int): Int {
return ourInstance.preferences!!.getInt(key, defaultValue)
}
fun getLong(key: String, defaultValue: Long): Long {
return ourInstance.preferences!!.getLong(key, defaultValue)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment