Skip to content

Instantly share code, notes, and snippets.

@shihabmi7
Created June 25, 2024 05:03
Show Gist options
  • Save shihabmi7/e35e73e9d170a9b76685bc660e927292 to your computer and use it in GitHub Desktop.
Save shihabmi7/e35e73e9d170a9b76685bc660e927292 to your computer and use it in GitHub Desktop.
Singletone AppsharedPreference
package com.emerico.acorreuserkotlin.utility
import android.content.Context
import android.content.SharedPreferences
object AppSharedPreference {
/** How to use
AppSharedPreference.putString(AppConstant.KEY_USER_NAME, "Shihab")
* AppSharedPreference.getString(AppConstant.KEY_USER_NAME)
*
* */
private val sharedPreferences: SharedPreferences = getApplication()
.getSharedPreferences(APP_NAME, Context.MODE_PRIVATE)
fun putString(key: String, value: String?) {
removeIfValueIsNull(key, value)
sharedPreferences.edit().putString(key, value).apply()
}
fun putInteger(key: String, value: Int?) {
removeIfValueIsNull(key, value)
if (value != null) {
sharedPreferences.edit().putInt(key, value).apply()
}
}
fun putBoolean(key: String?, value: Boolean?) {
sharedPreferences.edit().putBoolean(key, value!!).apply()
}
fun getString(key: String?): String? {
return sharedPreferences.getString(key, null)
}
fun getString(key: String?, setDefault: String?): String? {
return sharedPreferences.getString(key, setDefault)
}
fun getInteger(key: String?): Int {
return sharedPreferences.getInt(key, 0)
}
fun getInteger(key: String?, setDefault: Int): Int {
return sharedPreferences.getInt(key, setDefault)
}
fun getBoolean(key: String?): Boolean {
return sharedPreferences.getBoolean(key, false)
}
fun getBoolean(key: String?, setDefault: Boolean): Boolean {
return sharedPreferences.getBoolean(key, setDefault)
}
fun remove(key: String?) {
sharedPreferences.edit().remove(key).apply()
}
fun clearAllValues() {
sharedPreferences.edit().clear().apply()
}
private fun removeIfValueIsNull(key: String, value: Any?) {
if (value == null) {
this.remove(key)
}
}
}
class AcorreUserApplication : Application() {
override fun onCreate() {
super.onCreate()
application = this
AppSharedPreference.putString(AppConstant.KEY_USER_NAME, "Shihab")
}
companion object {
private lateinit var application: AcorreUserApplication
fun getApplication(): Application {
return application;
}
}
}
object AppConstant {
var APP_NAME: String = "AcorreUser"
var KEY_USER_NAME: String = "USER_NAME"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment