'How to keep user loged in using SharedPreferences in Kotlin?
i have a problem here, i want to make login and register using SharedPreferences. The pass and getting data is already done and no error, but idk how to keep user loged in and everytime user close the app it will automatically go to my HomeFragment. And user can go to login again if they click logout button in my HomeFragment
this is my LoginFragment
override fun onCreateView(
...
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.btnSignIn.setOnClickListener {
getPrefData()
}
binding.tvRegister.setOnClickListener{
navControllerRegister()
}
}
private fun getPrefData(){
...
}
private fun navControllerSignIn(){
...
}
private fun navControllerRegister(){
...
}
this is my HomeFragment
override fun onCreateView(
...
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val pref = requireActivity().getSharedPreferences(Data.Preferences.PREF_ID, Context.MODE_PRIVATE)
binding.btnLogOut.setOnClickListener {
val editor = pref.edit()
editor.remove(Data.Preferences.IS_LOGIN)
editor.clear()
val intent = Intent(requireActivity(), LoginFragment::class.java)
startActivity(intent)
}
}
and this is my constant data
object Data{
object Preferences{
const val PREF_ID = "CHALLENGE_CHAPTER_4"
const val IS_LOGIN = "IS_LOGIN"
const val PREF_NAME = "NAME"
const val PREF_EMAIL = "EMAIL"
const val PREF_PASS = "PASS"
const val PREF_CONFIRM_PASS = "CONFIRM_PASS"
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
