iT邦幫忙

2021 iThome 鐵人賽

DAY 20
0
自我挑戰組

Android kotlin &MVVM系列 第 20

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學習筆記19
下一篇
Android學習筆記21
系列文
Android kotlin &MVVM30

尚未有邦友留言

立即登入留言