简体   繁体   English

如何在 Android(MVVM、数据绑定、Kotlin)中实现“记住我”function?

[英]How to implement a “Remember me” function in Android(MVVM, Data Binding, Kotlin)?

  • I want to implement a "Remember me" function in AuthActivity我想在 AuthActivity 中实现一个“记住我”function

  • The way it must work is that when I enter correct user information it is going to be stored in SharedPreferences.它必须工作的方式是,当我输入正确的用户信息时,它将存储在 SharedPreferences 中。

  • So the next time I enter the app I must be in the next activity SelectWorkActivity, however if I want to go back to AuthActivity editTexts(inputs in AuthActivity) must have stored user information.所以下次我进入应用程序时,我必须在下一个活动 SelectWorkActivity 中,但是如果我想 go 回到 AuthActivity,editTexts(AuthActivity 中的输入)必须存储用户信息。

  • The structure of the app must follow the MVVM pattern no matter what无论如何,应用程序的结构必须遵循 MVVM 模式

  • Ask me any question you need.问我任何你需要的问题。

  • Pictures are provided down below as well as the code below the pictures.下面提供了图片以及图片下方的代码。

  • Thank you so much ahead if you contribute to the future solution of this problem.如果您为这个问题的未来解决方案做出贡献,非常感谢您。

AuthActivity(Authentication) AuthActivity(认证)

在此处输入图像描述

SelectWorkActivity(Just the next page) SelectWorkActivity(只是下一页)

在此处输入图像描述

AuthActivity()授权活动()

class AuthActivity : AppCompatActivity(), AuthListener {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val API = API()
    val Pref = PreferenceProvider(this)
    val repository = UserRepository(API, Pref)
    val factory = AuthViewModelFactory(repository)

    // Getting data from UI

    val binding: ActivityAuthBinding = DataBindingUtil.setContentView(this, R.layout.activity_auth)
    val viewModel = ViewModelProviders.of(this, factory).get(AuthViewModel::class.java)
    binding.authViewModel = viewModel

    //

    viewModel.authListener = this
    viewModel.onActivated()


}

override fun onStarted() {
    toast("Аутентификация в процессе...")


}

override fun onSuccess(user: ValueAuth) {
    toast("Работник ${user.fio} вошел в систему")
}

override fun onFailure(message: String) {
    toast(message)
}

override fun navigateToSelectWork() {

    val nav = Intent(applicationContext, SelectWorkActivity::class.java)
    startActivity(nav)

}

override fun errorLogin(errorMessage: String) {
    login_input.error = errorMessage
    refocusError(login_input)
}

override fun errorPassword(errorMessage: String) {
    password_input.error = errorMessage
    refocusError(password_input)
}



private fun refocusError(componentToFocus: View) {
    if(componentToFocus.requestFocus()){
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
    }

}

override fun onActivate(info: SharePrefData) {
    super.onResume()
    val (login, password, checked) = info
    login_input.setText(login)
    password_input.setText(password)
    checkBox.isChecked = checked

}

} }

AuthListener()授权监听器()

interface AuthListener {

fun onStarted()
fun onSuccess(user: ValueAuth)
fun onFailure(message: String)
fun navigateToSelectWork()
fun errorLogin(errorMessage: String)
fun errorPassword(errorMessage: String)
fun onActivate(info: SharePrefData)

} }

AuthViewModel()授权视图模型()

class AuthViewModel(
private val repository: UserRepository

): ViewModel() { ): 视图模型() {

var email: String? = null
var password: String? = null
var authListener: AuthListener? = null
var onChecked: Boolean? = false







fun onActivated (){


    var onChecked: Boolean = repository.getBoolean()
    if(onChecked == true){


        authListener?.onActivate(repository.getInfo())

        authIn()
    } else {
        authListener?.onFailure("Введите ваши данные")
    }

}

fun onCheckedClick(view: View){
    onChecked = true
}

fun authIn(){

    authListener?.onStarted()

    Coroutines.main {


        try {
            val authResponse = repository.userAuth(email!!, password!!)



            authResponse.value?.let {
                repository.saveAuth(email!!, password!!, onChecked!!)
                authListener?.navigateToSelectWork()
                authListener?.onSuccess(it)


                return@main
            }
            authListener?.onFailure("Ошибка: ${authResponse.result!!.errMsg}")

        } catch (error: APIException){
            authListener?.onFailure(error.message!!)
        }
    }

}


fun onLoginButtonClicked(view: View) {

    if(email.isNullOrEmpty())
    {
        authListener?.errorLogin("Заполните ваш логин")
        false

    }
    else if(password.isNullOrEmpty())
    {
        authListener?.errorPassword("Заполните ваш пароль")
        false

    }
    else
    {
        authIn()
    }
    
}

} }

UserRepository()用户存储库()

class  UserRepository(
private val API: API,
private val Preference: PreferenceProvider

): SaveAPIRequest() { ): SaveAPIRequest() {

 suspend fun userAuth(email: String, password: String): AuthResponse {

         return APIRequest { API.userAuth(email, password) }

}

fun saveAuth(email: String, password: String, checked: Boolean){
    Preference.saveLastSavedAuth(email, password, checked)

}


fun getBoolean(): Boolean
{
    return Preference.getBoolean()
}

fun getInfo(): SharePrefData
{
    return Preference.getInfo()
}

} }

PreferenceProvider()偏好提供者()

private const val LOGIN_SAVED = "KEY_TO_LOGIN_SAVED"

private const val PASSWORD_SAVED = "KEY_TO_PASSWORD_SAVED" private const val CHECKED = "KEY_TO_CHECKED_SAVED"私有 const val PASSWORD_SAVED = "KEY_TO_PASSWORD_SAVED" 私有 const val CHECKED = "KEY_TO_CHECKED_SAVED"

class PreferenceProvider( context: Context ){ private var appContext = context.applicationContext private val preference: SharedPreferences get() = PreferenceManager.getDefaultSharedPreferences(appContext) class PreferenceProvider( context: Context ){ private var appContext = context.applicationContext private val 首选项:SharedPreferences get() = PreferenceManager.getDefaultSharedPreferences(appContext)

fun saveLastSavedAuth(savedLogin: String, savedPassword: String, savedChecked: Boolean){
    preference.edit().putString(LOGIN_SAVED, savedLogin).apply()
    preference.edit().putString(PASSWORD_SAVED, savedPassword).apply()
    preference.edit().putBoolean(CHECKED, savedChecked).apply()
}

fun getBoolean(): Boolean{
    return preference.getBoolean(CHECKED, false)
}

fun getInfo(): SharePrefData {

    val login = preference.getString(LOGIN_SAVED, "")
    val password = preference.getString(PASSWORD_SAVED, "")
    val checked = preference.getBoolean(CHECKED, false)

    return SharePrefData(login, password, checked)

}

fun doNotSaveLastSavedAuth(){

    preference.edit().putString(LOGIN_SAVED, "").apply()
    preference.edit().putString(PASSWORD_SAVED, "").apply()
    preference.edit().putBoolean(CHECKED, false).apply()
}

} }

  • I want to implement a "Remember me" function in AuthActivity我想在 AuthActivity 中实现一个“记住我”function

  • The way it must work is that when I enter correct user information it is going to be stored in SharedPreferences.它必须工作的方式是,当我输入正确的用户信息时,它将存储在 SharedPreferences 中。

  • So the next time I enter the app I must be in the next activity SelectWorkActivity, however if I want to go back to AuthActivity editTexts(inputs in AuthActivity) must have stored user information.所以下次我进入应用程序时,我必须在下一个活动 SelectWorkActivity 中,但是如果我想 go 回到 AuthActivity,editTexts(AuthActivity 中的输入)必须存储用户信息。

  • The structure of the app must follow the MVVM pattern no matter what无论如何,应用程序的结构必须遵循 MVVM 模式

  • Ask me any question you need.问我任何你需要的问题。

  • Pictures are provided down below as well as the code below the pictures.下面提供了图片以及图片下方的代码。

  • Thank you so much ahead if you contribute to the future solution of this problem.如果您为这个问题的未来解决方案做出贡献,非常感谢您。

AuthActivity(Authentication) AuthActivity(认证)

在此处输入图像描述

SelectWorkActivity(Just the next page) SelectWorkActivity(只是下一页)

在此处输入图像描述

AuthActivity()授权活动()

class AuthActivity : AppCompatActivity(), AuthListener {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val API = API()
    val Pref = PreferenceProvider(this)
    val repository = UserRepository(API, Pref)
    val factory = AuthViewModelFactory(repository)

    // Getting data from UI

    val binding: ActivityAuthBinding = DataBindingUtil.setContentView(this, R.layout.activity_auth)
    val viewModel = ViewModelProviders.of(this, factory).get(AuthViewModel::class.java)
    binding.authViewModel = viewModel

    //

    viewModel.authListener = this
    viewModel.onActivated()


}

override fun onStarted() {
    toast("Аутентификация в процессе...")


}

override fun onSuccess(user: ValueAuth) {
    toast("Работник ${user.fio} вошел в систему")
}

override fun onFailure(message: String) {
    toast(message)
}

override fun navigateToSelectWork() {

    val nav = Intent(applicationContext, SelectWorkActivity::class.java)
    startActivity(nav)

}

override fun errorLogin(errorMessage: String) {
    login_input.error = errorMessage
    refocusError(login_input)
}

override fun errorPassword(errorMessage: String) {
    password_input.error = errorMessage
    refocusError(password_input)
}



private fun refocusError(componentToFocus: View) {
    if(componentToFocus.requestFocus()){
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
    }

}

override fun onActivate(info: SharePrefData) {
    super.onResume()
    val (login, password, checked) = info
    login_input.setText(login)
    password_input.setText(password)
    checkBox.isChecked = checked

}

} }

AuthListener()授权监听器()

interface AuthListener {

fun onStarted()
fun onSuccess(user: ValueAuth)
fun onFailure(message: String)
fun navigateToSelectWork()
fun errorLogin(errorMessage: String)
fun errorPassword(errorMessage: String)
fun onActivate(info: SharePrefData)

} }

AuthViewModel()授权视图模型()

class AuthViewModel(
private val repository: UserRepository

): ViewModel() { ): 视图模型() {

var email: String? = null
var password: String? = null
var authListener: AuthListener? = null
var onChecked: Boolean? = false







fun onActivated (){


    var onChecked: Boolean = repository.getBoolean()
    if(onChecked == true){


        authListener?.onActivate(repository.getInfo())

        authIn()
    } else {
        authListener?.onFailure("Введите ваши данные")
    }

}

fun onCheckedClick(view: View){
    onChecked = true
}

fun authIn(){

    authListener?.onStarted()

    Coroutines.main {


        try {
            val authResponse = repository.userAuth(email!!, password!!)



            authResponse.value?.let {
                repository.saveAuth(email!!, password!!, onChecked!!)
                authListener?.navigateToSelectWork()
                authListener?.onSuccess(it)


                return@main
            }
            authListener?.onFailure("Ошибка: ${authResponse.result!!.errMsg}")

        } catch (error: APIException){
            authListener?.onFailure(error.message!!)
        }
    }

}


fun onLoginButtonClicked(view: View) {

    if(email.isNullOrEmpty())
    {
        authListener?.errorLogin("Заполните ваш логин")
        false

    }
    else if(password.isNullOrEmpty())
    {
        authListener?.errorPassword("Заполните ваш пароль")
        false

    }
    else
    {
        authIn()
    }
    
}

} }

UserRepository()用户存储库()

class  UserRepository(
private val API: API,
private val Preference: PreferenceProvider

): SaveAPIRequest() { ): SaveAPIRequest() {

 suspend fun userAuth(email: String, password: String): AuthResponse {

         return APIRequest { API.userAuth(email, password) }

}

fun saveAuth(email: String, password: String, checked: Boolean){
    Preference.saveLastSavedAuth(email, password, checked)

}


fun getBoolean(): Boolean
{
    return Preference.getBoolean()
}

fun getInfo(): SharePrefData
{
    return Preference.getInfo()
}

} }

PreferenceProvider()偏好提供者()

private const val LOGIN_SAVED = "KEY_TO_LOGIN_SAVED"

private const val PASSWORD_SAVED = "KEY_TO_PASSWORD_SAVED" private const val CHECKED = "KEY_TO_CHECKED_SAVED"私有 const val PASSWORD_SAVED = "KEY_TO_PASSWORD_SAVED" 私有 const val CHECKED = "KEY_TO_CHECKED_SAVED"

class PreferenceProvider( context: Context ){ private var appContext = context.applicationContext private val preference: SharedPreferences get() = PreferenceManager.getDefaultSharedPreferences(appContext) class PreferenceProvider( context: Context ){ private var appContext = context.applicationContext private val 首选项:SharedPreferences get() = PreferenceManager.getDefaultSharedPreferences(appContext)

fun saveLastSavedAuth(savedLogin: String, savedPassword: String, savedChecked: Boolean){
    preference.edit().putString(LOGIN_SAVED, savedLogin).apply()
    preference.edit().putString(PASSWORD_SAVED, savedPassword).apply()
    preference.edit().putBoolean(CHECKED, savedChecked).apply()
}

fun getBoolean(): Boolean{
    return preference.getBoolean(CHECKED, false)
}

fun getInfo(): SharePrefData {

    val login = preference.getString(LOGIN_SAVED, "")
    val password = preference.getString(PASSWORD_SAVED, "")
    val checked = preference.getBoolean(CHECKED, false)

    return SharePrefData(login, password, checked)

}

fun doNotSaveLastSavedAuth(){

    preference.edit().putString(LOGIN_SAVED, "").apply()
    preference.edit().putString(PASSWORD_SAVED, "").apply()
    preference.edit().putBoolean(CHECKED, false).apply()
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM