Skip to content

Instantly share code, notes, and snippets.

@albaspazio
Last active December 18, 2020 10:12
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 albaspazio/14c999ff9c428afa2370173b747ef4b9 to your computer and use it in GitHub Desktop.
Save albaspazio/14c999ff9c428afa2370173b747ef4b9 to your computer and use it in GitHub Desktop.
Singleton solution to manage SharedPreferences
import android.content.Context
import androidx.preference.PreferenceManager
// concrete Singleton
object MyPrefManager: SharedPreferencePrimitives() {
// here specify preferences' names
private const val attachment = "attachment"
//call it once
fun init(context:Context, pref_name:String="", mode:Int = Context.MODE_PRIVATE){
if(isInitialized()) return // prevent multiple init
pref = if(pref_name.isEmpty()) PreferenceManager.getDefaultSharedPreferences(context)
else context.getSharedPreferences(pref_name, mode)
editor = pref.edit()
}
fun setAttachment(useattach: Boolean) {
attachment.put(useattach)
}
fun getAttachment() = attachment.getBoolean()
}
import android.content.SharedPreferences
abstract class SharedPreferencePrimitives(){
// both are initialized in subclasses
lateinit var editor:SharedPreferences.Editor
lateinit var pref: SharedPreferences
fun isInitialized() = ::pref.isInitialized && ::editor.isInitialized
protected fun String.put(long: Long) {
editor.putLong(this, long)
editor.commit()
}
protected fun String.put(int: Int) {
editor.putInt(this, int)
editor.commit()
}
protected fun String.put(string: String) {
editor.putString(this, string)
editor.commit()
}
protected fun String.put(boolean: Boolean) {
editor.putBoolean(this, boolean)
editor.commit()
}
protected fun String.getLong() = pref.getLong(this, 0)
protected fun String.getInt() = pref.getInt(this, 0)
protected fun String.getString() = pref.getString(this, "")!!
protected fun String.getBoolean() = pref.getBoolean(this, false)
fun clearData() {
if(!isInitialized()) return
editor.clear()
editor.commit()
}
fun removeKey(key:String){
if(!isInitialized()) return
editor.remove(key)
editor.commit()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment