skip to Main Content

I created a simple app with Kotlin in Android Studio. eEerything is OK and 0 errors in the whole app. but there is a little issue that experts can help me I know! so, I reviewed all similar questions like this in whole stack overflow, but they were not what I wanted at all, and they caused me to try many ways, but they do not help me. here is what I want:

I want when I log in with my email and password and it goes to dashboard activity, the app stays in DashboardActivity.kt but when I close the app and reopen it, the app is signed out and starts with login activity.

here are my codes:
ActivityMain.kt:

class MainActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
    initData()
}
private fun initData(){
    auth = FirebaseAuth.getInstance()
    checkIfUserIsLoggedIn()
}
private fun checkIfUserIsLoggedIn(){
    val currentUser = auth.currentUser
    if (currentUser != null){
        startActivity(Intent(this,DashbordActivity::class.java))
        finish()
    }else{
        startActivity(Intent(this,LoginActivity::class.java))
        finish()
    }
}
}

DashboardActivity.kt:

class DashbordActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var binding: ActivityDashbordBinding
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityDashbordBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
    initData()
}
private fun initData(){
    auth = FirebaseAuth.getInstance()
    setUserEmail()
    clickListener()
}
private fun clickListener(){
    binding.btnSignOut.setOnClickListener {
        auth.signOut()
        startActivity(Intent(this,LoginActivity::class.java))
        finish()
    }
}
private fun getCurrentUserEmail():String?{
    return  auth.currentUser?.email
}
private fun setUserEmail(){
    binding.tvUserEmail.text = "welcome " + getCurrentUserEmail()
}
}

LoginActivity.kt:

class LoginActivity : AppCompatActivity() {
private lateinit var binding: ActivityLoginBinding
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityLoginBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
    initData()
}
private fun initData(){
    auth = FirebaseAuth.getInstance()
    clickListener()
}
private fun clickListener(){
    binding.llNewUser.setOnClickListener {
        startActivity(Intent(this,RegisterActivity::class.java))
        finish()
    }
    binding.btnLogin.setOnClickListener {
        getUserData()
    }
}
private fun getUserData(){
    val email = binding.etEmail.text.toString()
    val password = binding.etPassword.text.toString()
    if (email.isNotEmpty() && password.isNotEmpty()){
        authUser(email,password)
    }else{
        Toast.makeText(this,"All inputs required ...",Toast.LENGTH_LONG).show()
    }
}
private fun authUser(email: String, password: String){
    auth.signInWithEmailAndPassword(email,password)
        .addOnCompleteListener {
            checkResult(it.isSuccessful)
        }
}
private fun checkResult(isSuccess: Boolean){
    if (isSuccess){
        startActivity(Intent(this,DashbordActivity::class.java))
        finish()
    }else{
        Toast.makeText(this,"Authentication failed ...",Toast.LENGTH_LONG).show()
    }
}
}

RegisterActivity.kt:

class RegisterActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var binding: ActivityRegisterBinding
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    auth = FirebaseAuth.getInstance()
    binding = ActivityRegisterBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
    initData()
}
private fun initData(){
    auth = FirebaseAuth.getInstance()
    clickListener()
}
private fun clickListener(){
    binding.btnRegister.setOnClickListener {
        createUser()
    }
    binding.llHaveAccount.setOnClickListener {

    }
}
private fun createUser(){
    val email = binding.etEmail.text.toString()
    val password = binding.etPassword.text.toString()
    val cPassword = binding.etcPassword.text.toString()
    if (email.isNotEmpty() && password.isNotEmpty() && cPassword.isNotEmpty()){
        if (password == cPassword){
            saveUser(email,password)

        }else{
            Toast.makeText(this,"Password mismatch",Toast.LENGTH_LONG).show()
        }
    }else{
        Toast.makeText(this,"All inputs required",Toast.LENGTH_LONG).show()
    }
}
private fun saveUser(email: String, password: String){
    auth.createUserWithEmailAndPassword(email,password)
        .addOnCompleteListener {
            checkResults(it.isSuccessful)
        }
}
private fun checkResults(isSuccess: Boolean){
    if (isSuccess){
        startActivity(Intent(this,LoginActivity::class.java))
        finish()
    }else{
        Toast.makeText(this,"Create to create your account",Toast.LENGTH_LONG).show()
    }
}
}

I say again: There is no error and app work perfect but when I login to app, it goes to DashboardActivity but when I close app and reopen it, it starts with LoginActivity. I want after login, it stays to DashboardActivity when I close and reopen the app.

thank you to whom help me:)

2

Answers


  1. As far as I understand from your question and your comments, the second time you open the app, the currentUser object is null, even if you were authenticated before. This is happening because the currentUser object is not updated in time. If you want to track the auth state, as also @FrankvanPuffelen mentioned in his comment, you have to use an AuthStateListener, which is called when there is a change in the authentication state. So according to the auth state, you should redirect the user to the corresponding activity.

    Since you’re using Kotlin, please see below an approach using Kotlin Coroutines:

    Login or Signup to reply.
  2. Firebase authentication does not save your login information that is why you get null from auth.currentUser whenever the app restarts. Sometimes it works for the firebase caching. For reliable & secure implementation, use the following to initiate the auth

    Firebase.auth.setPersistenceEnabled(true)
    

    this enables the auto sign in feature that you are trying to implement.
    Also, please implement the Firebase Auth with proper activity lifecycle for the secure & reliable result in both of your LoginActivity & ActivityMain. Refer to the official documentation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search