Native Mobile App Development With Java

Firebase Email Verification

03-Oct-2024

Firebase Email Verification


** Note Some Image text is blank for security purposes


Output:


     Login or register with a valid email address.
















Click on the Verify Email Button. A link will sent to your mailbox with the name noreply





After getting the mail click on the link you will be verified. Now restart your app. you will able to see your mail is verified.




















Now Let's start the project.


1/ Create an Empty Views Activity project: Firebase Email Verification


2/ Create another 2 activities one by one LoginActivity & RegisterActivity


3/ Modify your AnroidManifest.xml



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<uses-permission android:name="android.permission.INTERNET"/>

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.FirebaseEmailVerification"
tools:targetApi="31">
<activity
android:name=".RegisterActivity"
android:exported="false" />
<activity
android:name=".LoginActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:exported="true">
</activity>
</application>

</manifest>



4/ We will work with recently created activities after connecting the Firebase with the app.


5/ Go to Tools > Firebase




after clicking the firebase shown in the picture above the Firebase assistance tool window will open. then click on Authentication




after clicking on the Authentication, a new window will open click on authentication using Google [Java ]




then another new window will open. Click on Connect to Firebase



after clicking on Connect to Firebase you will redirect to your web browser. you must log in with your Gmail in the browser.


6/ Now create, connect, and authentication permission in the Firebase project


   6.1/ Click on the Create New project. after click a new window will open




  6.2/ Firebase automatically suggests you a name. then click on Continue





  6.3/ click on Continue







   6.4/ Select Default account for Firebase and click on Create Project. You project will start making.




  6.5/After completing the project, you will see the button Continue click on it





  6.6/ Then you will redirect to your project. and you will able to see a popup window here. click on Connect





6.7/ Close the project and again open your project from the console.


6.8/ On the sidebar from Build you can find the option Authentication. Click on it





6.7/After clicking on Authentication the new window for authentication will open. Click on Get Started





6.8/ Select Email/Password Provider from the new window. if not visible then click on the sign-in option and then click on Add Provider.





6.9/ Enable Email/Password Provider and Save it.




Here working with Firebase Project is Complete.


Now Go to your Android Studio You can see Firebase connected on the Firebase tool window where you left the last time


7/ Click on Add the Firebase Authentication SDK to your App. The new popup window will open



8/ Click on Accept Change. SDK will automatically add to your project.





Firebase Connection and SDK setup are complete. Now we will work with those activities.


9/ Modify your activity_login.xml:




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
tools:context=".LoginActivity">

<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
>
<LinearLayout
android:id="@+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">

<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Your Email here" />

<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Enter Your password here" />
</LinearLayout>

<Button
app:layout_constraintTop_toBottomOf="@+id/linearlayout"
android:layout_marginTop="16dp"
android:id="@+id/loginButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
/>
<TextView
android:id="@+id/or"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/loginButton"
app:layout_constraintStart_toStartOf="@id/loginButton"
app:layout_constraintEnd_toEndOf="@id/loginButton"
android:layout_marginTop="16dp"
android:text="OR"
android:textSize="22sp"
/>
<TextView
android:id="@+id/registerButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/or"
app:layout_constraintStart_toStartOf="@id/or"
app:layout_constraintEnd_toEndOf="@id/or"
android:layout_marginTop="16dp"
android:text="Create an account"
android:textSize="22sp"
android:textColor="#21608B"
/>
</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>



10/ Modify your LoginActivity.java:




package com.microappvalley.firebaseemailverification;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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

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 LoginActivity extends AppCompatActivity {
private EditText email, password;
private Button loginButton;
private TextView registerButton;
private FirebaseAuth auth;

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

email = findViewById(R.id.email);
password = findViewById(R.id.password);
loginButton = findViewById(R.id.loginButton);
registerButton = findViewById(R.id.registerButton);
auth = FirebaseAuth.getInstance();

loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String emailTxt = email.getText().toString();
String passwordTxt = password.getText().toString();
loginUser(emailTxt, passwordTxt);
}
});

registerButton.setOnClickListener(v -> {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
});
}

private void loginUser(String email, String password) {
auth.signInWithEmailAndPassword(email, password).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
Toast.makeText(LoginActivity.this, "Login failed.", Toast.LENGTH_SHORT).show();
}
});
}

@Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = auth.getCurrentUser();
if(currentUser != null){
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
}





11/ Modify your activity_register.xml:





<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
tools:context=".LoginActivity">

<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
>
<LinearLayout
android:id="@+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">

<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Your Email here" />

<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Enter Your password here" />
</LinearLayout>

<Button
app:layout_constraintTop_toBottomOf="@+id/linearlayout"
android:layout_marginTop="16dp"
android:id="@+id/registerButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Register"
/>
<TextView
android:id="@+id/or"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/registerButton"
app:layout_constraintStart_toStartOf="@id/registerButton"
app:layout_constraintEnd_toEndOf="@id/registerButton"
android:layout_marginTop="16dp"
android:text="OR"
android:textSize="22sp"
/>
<TextView
android:id="@+id/loginButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/or"
app:layout_constraintStart_toStartOf="@id/or"
app:layout_constraintEnd_toEndOf="@id/or"
android:layout_marginTop="16dp"
android:text="Login existing account"
android:textSize="22sp"
android:textColor="#21608B"
/>
</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>



12/ Modify your RegisterActivity.java:





package com.microappvalley.firebaseemailverification;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.auth.FirebaseAuth;

public class RegisterActivity extends AppCompatActivity {
private EditText email, password;
private Button registerButton;
private TextView loginButton;
private FirebaseAuth mAuth;

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

email = findViewById(R.id.email);
password = findViewById(R.id.password);
registerButton = findViewById(R.id.registerButton);
loginButton = findViewById(R.id.loginButton);

mAuth = FirebaseAuth.getInstance();

registerButton.setOnClickListener(v -> {
String emailTxt = email.getText().toString();
String passwordTxt = password.getText().toString();
registerUser(emailTxt, passwordTxt);
});

loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
});
}

private void registerUser(String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
intent.putExtra("email", FirebaseAuth.getInstance().getCurrentUser().getEmail());
startActivity(intent);
finish();
} else {
Toast.makeText(RegisterActivity.this, "Registration failed.", Toast.LENGTH_SHORT).show();
}
});
}
}



13/ Modify your activity_main.xml:




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:gravity="center"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/emailTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="22dp"/>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:layout_marginTop="8dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="is verified Email ? "
/>
<TextView
android:id="@+id/verifiedOrNot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Verified "
android:textStyle="bold"
/>
</LinearLayout>

<Button
android:id="@+id/verifyBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Verify Email"
android:layout_marginTop="16dp"
android:visibility="gone"
/>

<Button
android:id="@+id/logOut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Logout"/>

</LinearLayout>





14/ Modify your MainActivity.java:



package com.microappvalley.firebaseemailverification;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

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

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 TextView emailTxt, verifiedOrNot;
private Button verifyBtn, logOut;
private FirebaseAuth auth;

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

auth = FirebaseAuth.getInstance();

emailTxt = findViewById(R.id.emailTxt);
verifiedOrNot = findViewById(R.id.verifiedOrNot);
verifyBtn = findViewById(R.id.verifyBtn);
logOut = findViewById(R.id.logOut);


emailTxt.setText(auth.getCurrentUser().getEmail());

if (auth.getCurrentUser().isEmailVerified()) {
verifiedOrNot.setText("Verified");
verifyBtn.setVisibility(View.GONE);

} else {
verifiedOrNot.setText("Not Verified");
verifyBtn.setVisibility(View.VISIBLE);
}

logOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
auth.signOut();
finish();
}
});

verifyBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Verification email sent!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Failed to send verification email.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}

@Override
protected void onStart() {
super.onStart();

auth.getCurrentUser().reload().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (auth.getCurrentUser().isEmailVerified()) {
verifiedOrNot.setText("Verified");
verifyBtn.setVisibility(View.GONE);

} else {
verifiedOrNot.setText("Not Verified");
verifyBtn.setVisibility(View.VISIBLE);
}
}
});


}
}



Now run your app and test with a valid email address.





Comments