Util

Util SharedPreferences 儲存物件&儲存資料

SharedPreferences 工具類 儲存物件&儲存資料

  1. SharedInfo
  2. SPUtil
  3. 使用方法
  4. 效果展示

1.SharedInfo

import android.content.Context
import android.content.SharedPreferences

/**
 * Author: FlyWei
 * E-mail: tony91097@gmail.com
 * Date: 2021/4/28
 */

class SharedInfo private constructor() {

    private var sp: SharedPreferences

    companion object {
        val instance: SharedInfo by lazy { SharedInfo() }
        private lateinit var fileName: String
        private lateinit var context: Context

        fun init(fileName: String, context: Context) {
            this.fileName = fileName
            this.context = context
        }
    }

    init {
        sp = SPUtil.getSp(context, fileName)
    }

    /**
     * 獲取資料
     */
    fun <T> getEntity(clazz: Class<T>): T? =
        SPUtil.getEntity(sp, clazz)

    fun getValue(key: String, defaultValue: Any): Any? =
        SPUtil.getValue(sp, key, defaultValue)

    /**
     * 保存資料
     */
    fun saveEntity(any: Any) {
        SPUtil.saveEntity(sp, any)
    }

    fun saveValue(key: String, value: Any) {
        SPUtil.saveValue(sp, key, value)
    }

    /**
     * 刪除資料
     */
    fun remove(clazz: Class<*>) {
        SPUtil.remove(sp, clazz.name)
    }

    fun remove(key: String) {
        SPUtil.remove(sp, key)
    }

    /**
     * 清除資料
     */
    fun clear() {
        SPUtil.clear(sp)
    }
}

2.SPUtil

導入Gson做Serializable

implementation 'com.google.code.gson:gson:2.8.6'
import android.content.Context
import android.content.SharedPreferences
import android.util.Base64
import com.google.gson.Gson

/**
 * Author: FlyWei
 * E-mail: tony91097@gmail.com
 * Date: 2021/4/28
 */

object SPUtil {

    fun getSp(context: Context, fileName: String): SharedPreferences {
        return context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
    }

    fun saveValue(sp: SharedPreferences, key: String, value: Any) {
        val editor = sp.edit()
        when (value) {
            is String -> editor.putString(key, value).apply()
            is Boolean -> editor.putBoolean(key, value).apply()
            is Float -> editor.putFloat(key, value).apply()
            is Int -> editor.putInt(key, value).apply()
            is Long -> editor.putLong(key, value).apply()
            else -> require(value !is Set<*>) { "Value can not be Set object!" }
        }
    }

    fun getValue(sp: SharedPreferences, key: String, defaultValue: Any): Any? {
        when (defaultValue) {
            is String -> return sp.getString(key, defaultValue)
            is Boolean -> return sp.getBoolean(key, defaultValue)
            is Float -> return sp.getFloat(key, defaultValue)
            is Int -> return sp.getInt(key, defaultValue)
            is Long -> return sp.getLong(key, defaultValue)
            else -> require(defaultValue !is Set<*>) { "Can not to get Set value!" }
        }
        return null
    }

    fun saveEntity(sp: SharedPreferences, any: Any) {
        val key = any.javaClass.name
        val value = String(Base64.encode(obj2str(any).toByteArray(), Base64.DEFAULT))
        saveValue(sp, key, value)
    }

    fun <T> getEntity(sp: SharedPreferences, clazz: Class<T>): T? {
        val key = clazz.name
        var value = getValue(sp, key, "") as String
        value = String(Base64.decode(value, Base64.DEFAULT))
        return str2obj(value, clazz)
    }

    fun remove(sp: SharedPreferences, key: String) {
        sp.edit().remove(key).apply()
    }

    fun clear(sp: SharedPreferences) {
        sp.edit().clear().apply()
    }

    /**
     * Object 到 String 的序列化
     */
    private fun obj2str(any: Any): String {
        return try {
            Gson().toJson(any)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            ""
        }
    }

    /**
     * String 到 Object 的反序列化
     */
    private fun <T> str2obj(string: String, clazz: Class<T>): T? {
        return try {
            Gson().fromJson(string, clazz)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
}

3.使用方法

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 初始化(一定要)
        SharedInfo.init("info", applicationContext)

        //取得物件
        SharedInfo.instance.getEntity(Person::class.java)?.let {
            Log.e("GGG", it.name)
            Log.e("GGG", it.age.toString())
        }
        //取得資料
        val name = SharedInfo.instance.getValue("name", "no") as String
        Log.e("GGG", name)

        //儲存物件
        val person = Person("wade", 25)
        SharedInfo.instance.saveEntity(person)
        //儲存資料
        SharedInfo.instance.saveValue("name", "steven")

        //刪除物件&資料
        SharedInfo.instance.remove("name")
        SharedInfo.instance.remove(Person::class.java)

        //全部清空
        SharedInfo.instance.clear()
    }
}

4.效果展示

發表迴響