Firebase Authentication - 5 - Verify Email

Index

  1. Firebase setup
  2. Layout
  3. Register and Login
  4. Reset password
  5. Verify email
  6. Change profile picture
  7. Change display name
  8. Change email
  9. Change password
  10. Delete account

 

Welcome to the fifth Firebase Authentication series. In the previous part you learned how to reset passwords. In this part, I will show you how to verify emails. This will be be done in two different ways. First, when a user is registering a new account, a verification email will automatically be sent to that users email. The other way is from the main activity, if a user wants to resend the verification email for whatever reason. Let's start with the RegisterFragment.

 

RegisterFragment.java

package com.frogitecture.authenticatedgoose.Fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.frogitecture.authenticatedgoose.AuthActivity;
import com.frogitecture.authenticatedgoose.DialogFragments.LoadingDialog;
import com.frogitecture.authenticatedgoose.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class RegisterFragment extends Fragment {

    private LoadingDialog loadingDialog;
    private TextView loginTxt;
    private Button registerBtn;

    private EditText displayNameTxt;
    private EditText emailTxt;
    private EditText passwordTxt;

    private FirebaseAuth firebaseAuth;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View parentView = inflater.inflate(R.layout.fragment_register, container, false);
        loadingDialog = new LoadingDialog();

        loginTxt = parentView.findViewById(R.id.already_registered_txt);
        displayNameTxt = parentView.findViewById(R.id.display_name);
        emailTxt = parentView.findViewById(R.id.email);
        passwordTxt = parentView.findViewById(R.id.password);
        registerBtn = parentView.findViewById(R.id.register_btn);

        firebaseAuth = FirebaseAuth.getInstance();

        loginTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((AuthActivity) getActivity()).changeFragment(new LoginFragment());
            }
        });

        registerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadingDialog.setMessage("Registering...");
                loadingDialog.show(getActivity().getSupportFragmentManager(), "Signing In");

                final String displayName = displayNameTxt.getText().toString();
                String email = emailTxt.getText().toString();
                String password = passwordTxt.getText().toString();

                register(displayName, email, password);
            }
        });

        return parentView;
    }

    private void register(final String displayName, String email, String password) {
        firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            FirebaseUser user = firebaseAuth.getCurrentUser();

                            UserProfileChangeRequest profileChangeRequest = new UserProfileChangeRequest.Builder()
                                    .setDisplayName(displayName)
                                    .build();

                            // Add these lines
                            user.sendEmailVerification()
                                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {
                                            if (task.isSuccessful()) {
                                                Toast.makeText(getActivity(), "Verification email was sent", Toast.LENGTH_LONG).show();
                                            }
                                        }
                                    });

                            user.updateProfile(profileChangeRequest)
                                    .addOnCompleteListener(new OnCompleteListener<Void>() {

                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {
                                            loadingDialog.dismiss();
                                            getActivity().finish();
                                            startActivity(new Intent(getActivity(), MainActivity.class));
                                        }
                                    });

                        } else {
                            Toast.makeText(getActivity(), "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                        loadingDialog.dismiss();
                    }
                });
    }
}

Here, all we add is the method user.sendEmailVerification():

user.sendEmailVerification()
        .addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        if (task.isSuccessful()) {
            Toast.makeText(getActivity(), "Verification email was sent", Toast.LENGTH_LONG).show();
        }
    }
});

When an email is sent, we show a Toast message like we did in the previous part when a user sent an email to reset a password.

 

MainActivity.java

package com.frogitecture.authenticatedgoose;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.frogitecture.authenticatedgoose.DialogFragments.LoadingDialog;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {

    private FirebaseAuth firebaseAuth;
    private FirebaseUser firebaseUser;

    private ImageView imageView;
    private TextView displayNameTxt;
    private TextView useridTxt;
    private TextView emailTxt;
    private TextView verifiedTxt;
    private TextView sendVerificationTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        firebaseAuth = FirebaseAuth.getInstance();

        if (firebaseAuth.getCurrentUser() == null) {
            finish();
            startActivity(new Intent(this, AuthActivity.class));
            return;
        } else {
            firebaseUser = firebaseAuth.getCurrentUser();
        }

        imageView = findViewById(R.id.image);
        useridTxt = findViewById(R.id.uid_txt);
        displayNameTxt = findViewById(R.id.edittext);
        emailTxt = findViewById(R.id.email_txt);
        verifiedTxt = findViewById(R.id.verified_txt);
        sendVerificationTxt = findViewById(R.id.send_verification_txt);

        Uri profilePicture = firebaseUser.getPhotoUrl();
        String uid = firebaseUser.getUid();
        String displayName = firebaseUser.getDisplayName();
        final String email = firebaseUser.getEmail();
        String verifiedEmail = "No";

        // Add the else section
        if (firebaseUser.isEmailVerified()) {
            verifiedEmail = "Yes";
            sendVerificationTxt.setVisibility(View.GONE);
        } else {
            sendVerificationTxt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    firebaseAuth.sendPasswordResetEmail(email)
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()) {
                                        Toast.makeText(MainActivity.this, "Email sent! Check your inbox", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                }
            });
        }

        Glide.with(this).load(profilePicture).into(imageView);
        useridTxt.setText(uid);
        displayNameTxt.setText(displayName);
        emailTxt.setText(email);
        verifiedTxt.setText(verifiedEmail);

        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("Authenticated Goose");
        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.change_profile_picture:
                break;

            case R.id.change_display_name:
                break;

            case R.id.change_email:
                break;

            case R.id.change_password:
                break;

            case R.id.delete_account:
                break;

            case R.id.sign_out:
                FirebaseAuth.getInstance().signOut();
                finish();
                startActivity(new Intent(MainActivity.this, AuthActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

In MainActivity we add the else statement to the if (firebaseUser.isEmailVerified()):

if (firebaseUser.isEmailVerified()) {
    verifiedEmail = "Yes";
    sendVerificationTxt.setVisibility(View.GONE);
} else {
    sendVerificationTxt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            firebaseAuth.sendPasswordResetEmail(email)
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                Toast.makeText(MainActivity.this, "Email sent! Check your inbox", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
    });
}

If the email is verified, there's no point in showing the text "Click here to resend verification email", so we hide it with View.GONE and update the verifiedEmail TextView to "Yes". If it is not verified however, we add a click listener to that text and add the same code as we did in the RegisterFragment to send the verification email, with the method firebaseAuth.sendPasswordResetEmail(email).

In the next part I will show you how to change a profie picture. We will also add a welcome screen in the next part. The reason why I waited with the welcome screen is because choosing a profile picture is a big part of that fragment.

Author

authors profile photo

Articles with similar tags

thumbnail
Firebase Authentication - 7 - Change display name

Changing a display name in Android Studio with firebase auth

By Frogitecture

thumbnail
Firebase Authentication - 8 - Change email

Changing email in Android with Firebase Authentication

By Frogitecture

thumbnail
Firebase Authentication - 9 - Change password

Changing a password in Android with Firebase Authentication

By Frogitecture

thumbnail
Firebase Authentication - 10 - Delete account

Deleting an account in Android with Firebase Authentication

By Frogitecture