Last active
December 19, 2020 13:24
-
-
Save albaspazio/97cb957d8909841efc3095889ca0a54a to your computer and use it in GitHub Desktop.
Singleton SharedPreferences manager. Is based on general abstract class (SharedPreferenceWrapper) and a project-specific Singleton (ProjectPreferences)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.content.res.Resources | |
import androidx.preference.PreferenceManager | |
import org.albspazio.myproject.R | |
import org.albaspazio.core.sharedpreferences.SharedPreferenceWrapper | |
// this must be implemented for a specific project | |
object ProjectPreferences: SharedPreferenceWrapper() { | |
// init values of each Preference are stored in a specific resource. associate them! | |
private val keysHashMap:HashMap<String,Int> = hashMapOf( | |
"propr1" to R.integer.pref_propr1, | |
"propr2" to R.string.pref_propr2,) | |
private lateinit var resources: Resources | |
//call it once | |
fun init(context:Context, pref_name:String="", mode:Int = Context.MODE_PRIVATE){ | |
if(isInitialized()) return // prevent multiple init | |
prefs = if(pref_name.isEmpty()) PreferenceManager.getDefaultSharedPreferences(context) | |
else context.getSharedPreferences(pref_name, mode) | |
resources = context.resources | |
setDefault() | |
} | |
override fun read(key: String, value: Any): Any?{ | |
return if(!keysHashMap.contains(key) || !isInitialized()) null | |
else super.read(key, value) | |
} | |
override fun write(key: String, value: Any): Any?{ | |
return if(!keysHashMap.contains(key) || !isInitialized()) null | |
else super.write(key, value) | |
} | |
//============================================================================================== | |
// if a preference key is still unset, init it taking values from resources | |
private fun setDefault(){ | |
keysHashMap.map{ | |
if(!prefs.contains(it.key)) | |
when(it.key){ | |
"pref_propr1" -> write(it.key, resources.getInteger(it.value).toString()) | |
"pref_propr2" -> write(it.key, resources.getString(it.value)) | |
} | |
it | |
} | |
} | |
//============================================================================================== | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment