Kotlin安卓頁面本地存儲數據(方法和封裝)


直接上代碼

封裝:

 1 //存儲key對應的數據
 2 fun saveData(context: Activity, key: String, info: String) {
 3     val sharedPreferences = context.getSharedPreferences(key, MODE_PRIVATE)
 4     val editor = sharedPreferences.edit()
 5     editor.putString(key, info)
 6     editor.apply()
 7 }
 8 
 9 //取key對應的數據
10 fun getData(context: Activity, key: String): String {
11     val result = context.getSharedPreferences(key, MODE_PRIVATE).getString(key, "")
12     return if (result.isEmpty()) {
13         ""
14     } else {
15         result
16     }
17 }
18 
19 //清空緩存對應key的數據
20 fun clearData(context: Activity, key: String) {
21     context.getSharedPreferences(key, MODE_PRIVATE).edit().clear().apply()
22 }

這里第一個參數傳入Context,方便在各個activity/fragment里調用

 

調用:

1 //存數據
2 saveData(this@LoginActivity, "phone", _phone)
3 
4 //取數據
5 getData(this, "phone")
6 
7 //清除數據
8 clearData(activity!!,"phone")

 

ps:我這里都給轉成String封裝了,其實getSharedPreferences什么類型的都能存


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM