Created
December 21, 2018 12:56
-
-
Save cupatil/25a1da51e373e15e6e5d1340d7e65bef to your computer and use it in GitHub Desktop.
Singletone class of SharedPreferences
This file contains 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.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