MJV
MJV

Reputation: 722

How do I repeatedly check if the user is verified in the Firebase Authentication?

I want the program to repeatedly check if the user is verified in the Firebase Authentification until it is. For example, when the user makes an account on my application, the program switches into a new activity, waits until the user is verified, then automatically continues into the next activity.

I attempted to do this using a do while loop, but unfortunately, the program freezes and stays at a black screen. I never encountered any error messages along the way.

I tried the program with these lines of code:

EmailVerified = false;

do {
    if (mAuth.getCurrentUser().isEmailVerified()) {
        EmailVerified = true;
        Intent intent = new Intent(VerificationEmailPage.this, MainActivity.class);
        startActivity(intent);
    }
} while (!EmailVerified);

Doing this caused the activity not to load, and simply turn black. It seemed as if no other code was also executed in the activity. I needed the activity to load and constantly keep checking if the user is verified, then switch to the next activity once it was.

Upvotes: 1

Views: 1059

Answers (2)

samthecodingman
samthecodingman

Reputation: 26266

Building upon Doug's answer, this is the best method for doing what you want:

  1. Log in user (whether by sign in or creating an account).
  2. Start a "loading" activity, this activity gets the current user using a FirebaseAuth.AuthStateListener.
  3. In the onAuthStateChanged handler, check firebaseAuth.getCurrentUser().isEmailVerified().
  4. If the user is verified, send them to the next activity.
  5. If not, show a UI that asks the user to send a verification email.
  6. When the user presses the send button, send a verification email configured to point back to your application (see Passing State in Email Actions).
  7. When the user hits the URL from the verification email, check their isEmailVerified() state again.
  8. Jump back to step 4.

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317760

What you're doing now is not a good idea at all. Instead, you should be using an AuthStateListener to find out when the user is signed in.

mAuthListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            // Sign in logic here.
        }
    }
};

// activate it:
FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);

// deactivate it:
FirebaseAuth.getInstance().removeAuthStateListener(mAuthListener);


The listener will get invoked any time the user is signed in or out, until the listener is removed.

Read more about how it works: How does the firebase AuthStateListener work?

Upvotes: 3

Related Questions