Convert SharePreferences Android sang kotlin
This post hasn't been updated for 6 years
Những gì cần tìm hiểu đã có hết trong bài viết này rồi:
https://viblo.asia/p/toi-uu-android-shared-preferences-924lJM8bZPM
Hôm nay mình sẽ mạn phép dùng bài viết của tác giả ở trên để hướng dẫn các bạn convert SharePreferences của Android sang Kotlin
1.1. Phần khởi tạo SharedPrefs
companion object {
private val PREFS_NAME = "share_prefs"
private var mInstance: SharedPrefs? = null
val instance: SharedPrefs
get() {
if (mInstance == null) {
mInstance = SharedPrefs()
}
return mInstance as SharedPrefs
}
}
1.2. Put data vào shared preferences
Cần truyền vào key và gía trị vào -> function sẽ check type data và put vào đúng type
fun <T> put(key: String, data: T) {
val editor = mSharedPreferences.edit()
when (data) {
is String -> editor.putString(key, data as String)
is Boolean -> editor.putBoolean(key, data as Boolean)
is Float -> editor.putFloat(key, data as Float)
is Int -> editor.putInt(key, data as Int)
is Long -> editor.putLong(key, data as Long)
else -> editor.putString(key, App.self()?.gSon?.toJson(data))
}
editor.apply()
}
1.3. Get data từ shared preferencesype
- Cần truyền vào key và type class vào -> function sẽ check type class và get ra đúng giá trị
- Có 2 cách get data ra là get có giá trị mặc định được truyền vào và get có giá trị mặc định sẵn
@Suppress("UNCHECKED_CAST")
operator fun <T> get(key: String, anonymousClass: Class<T>): T {
return when (anonymousClass) {
String::class.java -> mSharedPreferences.getString(key, "") as T
Boolean::class.java -> java.lang.Boolean.valueOf(mSharedPreferences.getBoolean(key, false)) as T
Float::class.java -> java.lang.Float.valueOf(mSharedPreferences.getFloat(key, 0f)) as T
Int::class.java -> Integer.valueOf(mSharedPreferences.getInt(key, 0)) as T
Long::class.java -> java.lang.Long.valueOf(mSharedPreferences.getLong(key, 0)) as T
else -> App.self()?.gSon?.fromJson(mSharedPreferences.getString(key, ""), anonymousClass)!!
}
}
@Suppress("UNCHECKED_CAST")
operator fun <T> get(key: String, anonymousClass: Class<T>, defaultValue: T): T {
return when (anonymousClass) {
String::class.java -> mSharedPreferences.getString(key, defaultValue as String) as T
Boolean::class.java -> java.lang.Boolean.valueOf(mSharedPreferences.getBoolean(key, defaultValue as Boolean)) as T
Float::class.java -> java.lang.Float.valueOf(mSharedPreferences.getFloat(key, defaultValue as Float)) as T
Int::class.java -> Integer.valueOf(mSharedPreferences.getInt(key, defaultValue as Int)) as T
Long::class.java -> java.lang.Long.valueOf(mSharedPreferences.getLong(key, defaultValue as Long)) as T
else -> App.self()?.gSon?.fromJson(mSharedPreferences.getString(key, ""), anonymousClass)!!
}
}
Full code :
class SharedPrefs private constructor() {
private val mSharedPreferences: SharedPreferences
init {
mSharedPreferences = App.self()!!.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
}
@Suppress("UNCHECKED_CAST")
operator fun <T> get(key: String, anonymousClass: Class<T>): T {
return when (anonymousClass) {
String::class.java -> mSharedPreferences.getString(key, "") as T
Boolean::class.java -> java.lang.Boolean.valueOf(mSharedPreferences.getBoolean(key, false)) as T
Float::class.java -> java.lang.Float.valueOf(mSharedPreferences.getFloat(key, 0f)) as T
Int::class.java -> Integer.valueOf(mSharedPreferences.getInt(key, 0)) as T
Long::class.java -> java.lang.Long.valueOf(mSharedPreferences.getLong(key, 0)) as T
else -> App.self()?.gSon?.fromJson(mSharedPreferences.getString(key, ""), anonymousClass)!!
}
}
@Suppress("UNCHECKED_CAST")
operator fun <T> get(key: String, anonymousClass: Class<T>, defaultValue: T): T {
return when (anonymousClass) {
String::class.java -> mSharedPreferences.getString(key, defaultValue as String) as T
Boolean::class.java -> java.lang.Boolean.valueOf(mSharedPreferences.getBoolean(key, defaultValue as Boolean)) as T
Float::class.java -> java.lang.Float.valueOf(mSharedPreferences.getFloat(key, defaultValue as Float)) as T
Int::class.java -> Integer.valueOf(mSharedPreferences.getInt(key, defaultValue as Int)) as T
Long::class.java -> java.lang.Long.valueOf(mSharedPreferences.getLong(key, defaultValue as Long)) as T
else -> App.self()?.gSon?.fromJson(mSharedPreferences.getString(key, ""), anonymousClass)!!
}
}
fun <T> put(key: String, data: T) {
val editor = mSharedPreferences.edit()
when (data) {
is String -> editor.putString(key, data as String)
is Boolean -> editor.putBoolean(key, data as Boolean)
is Float -> editor.putFloat(key, data as Float)
is Int -> editor.putInt(key, data as Int)
is Long -> editor.putLong(key, data as Long)
else -> editor.putString(key, App.self()?.gSon?.toJson(data))
}
editor.apply()
}
fun clear() {
mSharedPreferences.edit().clear().apply()
}
companion object {
private val PREFS_NAME = "share_prefs"
private var mInstance: SharedPrefs? = null
val instance: SharedPrefs
get() {
if (mInstance == null) {
mInstance = SharedPrefs()
}
return mInstance as SharedPrefs
}
}
2. Khởi tạo App class
class App : Application() {
var gSon: Gson? = null
override fun onCreate() {
super.onCreate()
mSelf = this
gSon = Gson()
}
companion object {
private var mSelf: App? = null
fun self(): App? {
return mSelf
}
}
}
và chú ý khai báo trong AndroidManifest nhé
android:name=".App"
cũng như import thư viện gson trong build.gradle của app nữa nhé
implementation 'com.google.code.gson:gson:2.8.2'
3. Ứng dụng vào demo nhé
3.1. Tạo model Employee
Kotlin hỗ trợ chúng ta rất nhiều trong việc loại bỏ các hàm get set như trong java cũ
class Employee(var id: Long, var name: String?) {
override fun toString(): String {
return "Employee {" +
"id = " + id +
", name = '" + name + '\'' +
'}'
}
}
3.2. MainActivity
class MainActivity : AppCompatActivity() {
private val tag = this@MainActivity.javaClass.name!!
private val firstStaff = "first_staff"
private val secondStaff = "second_staff"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val employee = Employee(1, "Nguyen Viet Manh")
val employee2 = Employee(2, "Do Xuan Duc")
SharedPrefs.instance.put(firstStaff, employee)
SharedPrefs.instance.put(secondStaff, employee2)
Log.e(tag, SharedPrefs.instance[firstStaff, Employee::class.java].toString())
Log.e(tag, SharedPrefs.instance[secondStaff, Employee::class.java].toString())
Log.e(tag, SharedPrefs.instance["hello", Int::class.java, 2].toString())
}
}
Ảnh
Tham khảo
https://viblo.asia/p/toi-uu-android-shared-preferences-924lJM8bZPM
All Rights Reserved