Android学习笔记20

今天用了sharedpreferences,在mvvm架构上要使用respository来当作model来传递资料
那sharedpreference如果不是写在activity记得要把context传进建构值

class Repository (context: Context){

    private val sharedPreferences = context.getSharedPreferences("User", Context.MODE_PRIVATE)
    private val editor = sharedPreferences.edit()

    fun savedpreferences(account:String , password:String){
        editor.putString("account",account).putString("password",password).commit()
    }

    fun getpreferences(): SharedPreferences? {
        return sharedPreferences
    }

    fun clearpreference(){
        editor.clear().commit()
    }

}

然後是viewmodel

class MainViewModel(application: Application): AndroidViewModel(application) {

    fun saveddata(account: String, password: String) {
        Repository(getApplication()).savedpreferences(account,password)
    }

    fun getdata(){
        val account = Repository(getApplication()).getpreferences()!!.getString("account","")
        val password = Repository(getApplication()).getpreferences()!!.getString("password","")
        Toast.makeText(getApplication(),account+password,Toast.LENGTH_SHORT).show()
    }

    fun cleardata(){
        Repository(getApplication()).clearpreference()
    }
}

还有一个在activity监听的按钮

viewModel.result.observe(this){
    when(it){
        is MainDialogResult.Ok ->{
            mainViewModel.saveddata(it.account,it.password)
        }
        is MainDialogResult.Cancel ->{
            Toast.makeText(this,"cancel",Toast.LENGTH_SHORT).show()
        }
    }
}

成果如下
https://ithelp.ithome.com.tw/upload/images/20210929/20141791Kp1mpC2SSz.png
https://ithelp.ithome.com.tw/upload/images/20210929/20141791LQJQ92V6Ss.png
clear之後
https://ithelp.ithome.com.tw/upload/images/20210929/20141791S1geTHpNw6.png


<<:  [Android Studio 30天自我挑战] SeekBar元件介绍

>>:  Day 14 Docker 操作

JS 21 - 资料太多看得心很累?用 9 行程序码将资料转换为表格吧!

大家好! 光是复杂的 JSON 资料就要看到眼花了,如果又全部缩成一行,我不敢说了。 我们进入今天的...

任务开发检讨

我理想的情况是, 事前planing好API(req、res),完成每只api估时,妥善把开发过程分...

课堂笔记 - 物联网概论(3.5)

网路层(2) 3.zigbee ZigBee是一个短距离的通讯由ZigBee联盟所制定的一个无线传...

防止使用者频繁送出 Request & 倒数计时重新发送认证码

以实务来说,总是会有一些情况导致使用者没办法正常收到认证码,所以系统必须具备 retry on fa...

[Day29]程序菜鸟自学C++资料结构演算法 – 桶排序法(Bucket sort)

前言:桶排序又名箱排序,究竟这个特殊的排序法是怎麽运作的,让我们一来探讨! 桶排序: 和上一篇的基数...