Skip to content

Instantly share code, notes, and snippets.

@cupatil
Created December 21, 2018 12:56
Show Gist options
  • Save cupatil/25a1da51e373e15e6e5d1340d7e65bef to your computer and use it in GitHub Desktop.
Save cupatil/25a1da51e373e15e6e5d1340d7e65bef to your computer and use it in GitHub Desktop.
Singletone class of SharedPreferences
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.SharedPreferences
@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
@SuppressLint("CommitPrefEdits")
class PreferenceManager() {
companion object {
private val sharePref = PreferenceManager()
private var mSharedPreferences: SharedPreferences? = null
private var editor: SharedPreferences.Editor? = null
//The context passed into the getInstance should be application level context.
fun getInstance(context: Context): PreferenceManager {
if (mSharedPreferences == null) {
mSharedPreferences = context.getSharedPreferences(context.packageName, Activity.MODE_PRIVATE)
}
return sharePref
}
}
fun setStringValue(key: String, value: String) {
editor = mSharedPreferences!!.edit()
editor!!.putString(key, value)
editor!!.apply()
}
fun getStringValue(key: String): String {
return mSharedPreferences!!.getString(key, "")
}
fun setIntValue(key: String, value: Int) {
editor = mSharedPreferences!!.edit()
editor!!.putInt(key, value)
editor!!.apply()
}
fun getIntValue(key: String): Int {
return mSharedPreferences!!.getInt(key, 0)
}
fun setBooleanValue(key: String, value: Boolean) {
editor = mSharedPreferences!!.edit()
editor!!.putBoolean(key, value)
editor!!.apply()
}
fun getBooleanValue(key: String): Boolean {
return (mSharedPreferences as SharedPreferences).getBoolean(key, false)
}
fun saveMultipleData(stringHashMap: HashMap<String, String>) {
editor = mSharedPreferences!!.edit()
for (key in stringHashMap.keys) {
editor!!.putString(key, stringHashMap[key])
}
editor!!.apply()
}
fun clearSharedPreferences() {
editor = mSharedPreferences!!.edit()
editor!!.clear()
editor!!.apply()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment