cetinajero
cetinajero

Reputation: 347

Using Kotlin and Firebase to trigger a sendEmailVerification with onAuthStateChanged callback

I'm starting a new Android project and decided to use Kotlin and Firebase within, right now I'm able to create users successfully using createUserWithEmailAndPassword on my SignupActivity and my users are logged in successfully when createUserWithEmailAndPassword is finished.

Now I'm trying to get it further using the callback event that is triggered on FirebaseAuth.AuthStateListener using onAuthStateChanged(FirebaseAuth auth) but the listener that I'm creating inside my onCreate(savedInstanceState: Bundle?)function isn't get triggered and my lack of experience converting Java code to Kotlin isn't helping me to identify the root problem.

I have some Java example code to base on that goes like this:

Java example

onCreate(...//
mAuthListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            // User is signed in
            // NOTE: this Activity should get onpen only when the user is not signed in, otherwise
            // the user will receive another verification email.
            sendVerificationEmail();
        } else {
            // User is signed out

        }
        // ...
    }
};

My Kotlin code

    FirebaseAuth.AuthStateListener { auth ->
        val user = auth.currentUser
        if(user != null){
            // User is signed in
            Log.d(TAG, "Signed in")
            Toast.makeText(this, "User", Toast.LENGTH_LONG).show();
            sendVerificationEmail()
        }else{
            // User is signed out
            Log.d(TAG, "Signed out")
            Toast.makeText(this, "Null", Toast.LENGTH_LONG).show();
        }
    }

I put some log and toast elements for debugging purpose but neither of them are getting triggered, I'm thinking that the onAuthStateChanged is missing inside the FirebaseAuth.AuthStateListener but I don't know how to fix it.

If anyone can give me some advice on what I'm doing wrong it'll be much appreciate.

Thanks in advance.

Upvotes: 3

Views: 2313

Answers (1)

khusrav
khusrav

Reputation: 5307

This is what has helped me, pay attention on the parenthesis when calling addAuthStateListener - being new to kotlin I used { } curly ones:

    public override fun onStart() {
      super.onStart()
      firebaseAuth.addAuthStateListener(authStateListener)
    }

    public override fun onPause() {
       super.onPause()
       firebaseAuth.removeAuthStateListener(authStateListener)
    }

Upvotes: 3

Related Questions