skip to Main Content

I want that if a user is already logged in, another activity is loaded and displayed. All in all, it all works. The only problem is that I get to see the SignIn Activity for about 2 seconds instead of the MainActivity directly. How can I change this behavior?

   override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    auth = Firebase.auth
    userAlreadyLoggedIn()

    //Is shown for 2seconds
    binding = ActivitySignInBinding.inflate(layoutInflater)
    setContentView(binding.root)   
  }



    private fun userAlreadyLoggedIn(){        
    val currentUser = auth.currentUser
    if(currentUser != null){
        var db:FirebaseFirestore = FirebaseFirestore.getInstance()
        val userRef = db.collection(KEY_COLLECTION_USER).document(auth.currentUser!!.uid)

        userRef.get().addOnSuccessListener {document ->
            if(document !== null)
            {
                val intent = Intent(applicationContext,MainActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
                startActivity(intent)
            }
        }
        
      }
   }

2

Answers


  1. Try if below code works:

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = ActivitySignInBinding.inflate(layoutInflater)
            setContentView(binding.root)
            userAlreadyLoggedIn()  
        }
    
        private fun userAlreadyLoggedIn(){        
            val currentUserID = getCurrentUserID()
                if (currentUserID.isNotEmpty()) {
                    startActivity(Intent(this@SignInActivity, MainActivity::class.java))
                } else {
                      // Do something if log in fails.
                }
        }
    
        fun getCurrentUserID(): String {
            val currentUser = FirebaseAuth.getInstance().currentUser
            var currentUserID = ""
            if (currentUser != null) {
                currentUserID = currentUser.uid
            }
            return currentUserID
        }
                    
    
    Login or Signup to reply.
  2. Because you call start MainActivity in SignInActivity, so it will always run onCreate of SignInActivity, then start MainActivity.

    You should have a SplashActivity, in that, check user is logged in or not.
    If user logged in, show MainActivity else show SignInActivity

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