Add Firebase Authentication to Android Project (Java)

In this tutorial you will learn to make most out of Firebase Authentication. This would definitely give you kick start to Firebase.

In this article, we will create a app to be able to create a new user which will be authenticated using the Firebase authentication. Firebase Auth offers a variety of ways to authenticate users. Here, we are going to be discussing Email Password, also known as Email and Password Sign In. Firebase Authentication’s login process is easier than other login processes. This project includes login process, login process with any email and password reset processes. To get most of it, readers should try to understand the code and then implement them in app. Though at the end of article, you will find repo of github project which you can fork it and run on your device.

Foremost let’s set up Google Firebase Account and Google Developer Account.

Login to your Google Account then go to the https://firebase.google.com, click on “Go to Console” .

Step 1) On google console page Add New Project

Step 2) Let’s use default settings

Step 3) Use your Default account for now

And yeah our first project is ready to go, some minor configurations are yet to be done. Some one time additional configurations like choose country for Google Analytics would be asked.

This is main Dashboard of Project, for now in this article we will focus on Authentication System, so go to the authentication configuration and get started with the Authentication.

Step 4) Choose Email/Password under Native Provider also able both option. After choosing the Authentication menu and click on the sign-in method. Check the following image for more information how will it be after enabling it.

Step 5) After setting up SignIn Google Part lets configure android configuration part. First click on the project overview then click on Android logo.

Register your app, let debug signing certificate blank for now

For the package name, paste in your package name,mine is com.amanthebreaker.firebaselogin so it matches the package name from the your android project. Let debug signing certificate blank for now. You can find this in your app’s AndroidManifest.xml file.

Please don’t forget to add the google services json file to your Android project.

Add here google-services.json

So far we have covered the Firebase configuration part of the project. Now we will deep dive into Android Part.

Step 1) First create new Android project choose primary language as Java, select empty activity or If you want to add this login feature to your existing project then create an new empty activity. You can also connect to firebase from Android Studio through Assistant tool. But I wouldn’t recommend for beginner as assistant tool do lot of it’s dependencies work itself.

Step 2) Add below code line to build.gradle file.(project level)

dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
    classpath 'com.google.gms:google-services:3.2.0'
    

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

Step 3) Sync below dependencies to app build.gradle file (app level)

// app build.gradle
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.google.firebase:firebase-auth:11.8.0'
    implementation 'com.google.android.gms:play-services-auth:11.8.0'
}
apply plugin: 'com.google.gms.google-services'

Step 4) Add internet permission in Android Manifest file.

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

Step 5) Splash Screen

Splash Screen

XML Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:orientation="vertical"
    tools:context=".WelcomeActivity">

    <TextView
        android:id="@+id/Title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#F1F1F1"
        android:text="@string/app_name"
        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/signUpPageTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#F1F1F1"
        android:text="@string/welcome"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        android:textColor="@android:color/black" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/welcomeSignInButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginTop="12dp"
            android:text="@string/sign_in" />

        <Button
            android:id="@+id/welcomeSignUpButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@id/welcomeSignInButton"
            android:layout_centerInParent="true"
            android:text="@string/sign_up" />
    </RelativeLayout>

</LinearLayout>

Add these String values to strings.xml in resource

XML Code :

<resources>
    <string name="app_name">FirebaseLogin</string>
    <string name="welcome">Welcome</string>
    <string name="sign_up">Sign Up</string>
    <string name="sign_in">Sign In</string>
    <string name="TandC">I agree to the terms and condition of the AppCompany</string>
    <string name="error_view">Error View</string>
    <string name="password">Password</string>
    <string name="email_hint">[email protected]</string>
    <string name="email">Email</string>
    <string name="forgot_password">Forgot Password</string>
    <string name="email_verify_again">Send Verify Email Again</string>
    <string name="enterEmailId">Enter the registered Email ID</string>
    <string name="reset_password">Reset Password</string>
    <string name="user_domain_com">[email protected]</string>
</resources>

Java Code

Have look at the condition

package com.amanthebreaker.firebaselogin;

import androidx.appcompat.app.AppCompatActivity;

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

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;

public class WelcomeActivity extends AppCompatActivity {


    public Integer REQUEST_EXIT = 9;
    public FirebaseAuth mAuth;
    public FirebaseUser currentUser;
    Button signUpButton;
    Button signInButton;

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

        mAuth = FirebaseAuth.getInstance();

        signUpButton = findViewById(R.id.welcomeSignUpButton);
        signInButton = findViewById(R.id.welcomeSignInButton);

        signInButton.setVisibility(INVISIBLE);
        signUpButton.setVisibility(INVISIBLE);
        // here we check if the user previously signed in or not 
        // this condition decides whether to ask user to sign in or sign out        
        if (mAuth.getCurrentUser() != null) {
            mAuth.getCurrentUser().reload().addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {

                    currentUser = mAuth.getCurrentUser();


                    if (currentUser != null && currentUser.isEmailVerified()) {


                        System.out.println("Email Verified : " + currentUser.isEmailVerified());

                        Intent MainActivity = new Intent(WelcomeActivity.this, MainActivity.class);
                        startActivity(MainActivity);
                        WelcomeActivity.this.finish();


                    }
                }
            });

        } else {

            signInButton.setVisibility(VISIBLE);
            signUpButton.setVisibility(VISIBLE);

            System.out.println("user not available");

        }

        signUpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                Intent signUpIntent = new Intent(WelcomeActivity.this, SignUpActivity.class);

                startActivity(signUpIntent);


            }
        });


        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                Intent signInIntent = new Intent(WelcomeActivity.this, SignInActivity.class);

                startActivityForResult(signInIntent, REQUEST_EXIT);


            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_EXIT) {
            if (resultCode == RESULT_OK) {
                this.finish();

            }
        }
    }



}

Step 6) Create Account/Register with E-mail & Password or Sign Up

Sigin Up/Register

XML Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:orientation="vertical"
    tools:context=".SignUpActivity">


    <TextView
        android:id="@+id/Title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#F1F1F1"
        android:text="@string/app_name"
        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/signUpPageTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#F1F1F1"
        android:text="@string/sign_up"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        android:textColor="@android:color/black" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/signUpEmailTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/email"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

        <EditText
            android:id="@+id/signUpEmailTextInput"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:autofillHints=""
            android:ems="10"
            android:hint="@string/email_hint"
            android:inputType="textEmailAddress"
            tools:targetApi="o" />

        <TextView
            android:id="@+id/SignUpPasswordTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/password"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

        <EditText
            android:id="@+id/signUpPasswordTextInput"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:autofillHints=""
            android:ems="10"
            android:hint="@string/password"
            android:inputType="textPassword"
            tools:targetApi="o" />

        <CheckBox
            android:id="@+id/agreementCheckbox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/TandC" />

        <Button
            android:id="@+id/signUpButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/sign_up" />

        <TextView
            android:id="@+id/signUpErrorView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/error_view" />

    </LinearLayout>


</LinearLayout>

Java Code

package com.amanthebreaker.firebaselogin;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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;


public class SignUpActivity extends AppCompatActivity {


    private static final String TAG = "SignUpActivity";
    public FirebaseAuth mAuth;
    Button signUpButton;
    EditText signUpEmailTextInput;
    EditText signUpPasswordTextInput;
    CheckBox agreementCheckBox;
    TextView errorView;

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


        mAuth = FirebaseAuth.getInstance();

        signUpEmailTextInput = findViewById(R.id.signUpEmailTextInput);
        signUpPasswordTextInput = findViewById(R.id.signUpPasswordTextInput);
        signUpButton = findViewById(R.id.signUpButton);
        agreementCheckBox = findViewById(R.id.agreementCheckbox);
        errorView = findViewById(R.id.signUpErrorView);


        signUpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (signUpEmailTextInput.getText().toString().contentEquals("")) {


                    errorView.setText("Email cannot be empty");


                } else if (signUpPasswordTextInput.getText().toString().contentEquals("")) {


                    errorView.setText("Password cannot be empty");


                } else if (!agreementCheckBox.isChecked()) {

                    errorView.setText("Please agree to terms and Condition");


                } else {


                    mAuth.createUserWithEmailAndPassword(signUpEmailTextInput.getText().toString(), signUpPasswordTextInput.getText().toString()).addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {

                            if (task.isSuccessful()) {
                                // Sign in success, update UI with the signed-in user's information
                                Log.d(TAG, "createUserWithEmail:success");
                                FirebaseUser user = mAuth.getCurrentUser();

                                try {
                                    if (user != null)
                                        user.sendEmailVerification()
                                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                                    @Override
                                                    public void onComplete(@NonNull Task<Void> task) {
                                                        if (task.isSuccessful()) {
                                                            Log.d(TAG, "Email sent.");

                                                            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                                                                    SignUpActivity.this);

                                                            // set title
                                                            alertDialogBuilder.setTitle("Please Verify Your EmailID");

                                                            // set dialog message
                                                            alertDialogBuilder
                                                                    .setMessage("A verification Email Is Sent To Your Registered EmailID, please click on the link and Sign in again!")
                                                                    .setCancelable(false)
                                                                    .setPositiveButton("Sign In", new DialogInterface.OnClickListener() {
                                                                        public void onClick(DialogInterface dialog, int id) {

                                                                            Intent signInIntent = new Intent(SignUpActivity.this, SignInActivity.class);
                                                                            SignUpActivity.this.finish();
                                                                        }
                                                                    });

                                                            // create alert dialog
                                                            AlertDialog alertDialog = alertDialogBuilder.create();

                                                            // show it
                                                            alertDialog.show();


                                                        }
                                                    }
                                                });

                                } catch (Exception e) {
                                    errorView.setText(e.getMessage());
                                }
                            } else {
                                // If sign in fails, display a message to the user.
                                Log.w(TAG, "createUserWithEmail:failure", task.getException());
                                Toast.makeText(SignUpActivity.this, "Authentication failed.",
                                        Toast.LENGTH_SHORT).show();

                                if (task.getException() != null) {
                                    errorView.setText(task.getException().getMessage());
                                }

                            }

                        }
                    });

                }

            }
        });



    }
}

Step 7) SignIn Activity

Sign In

XML Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:orientation="vertical"
    tools:context=".SignInActivity">


    <TextView
        android:id="@+id/Title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#F1F1F1"
        android:text="@string/app_name"
        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/signUpPageTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#F1F1F1"
        android:text="@string/sign_in"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        android:textColor="@android:color/black" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/signInEmailTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/email"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

        <EditText
            android:id="@+id/signInEmailTextInput"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:autofillHints=""
            android:ems="10"
            android:hint="@string/email_hint"
            android:inputType="textEmailAddress"
            tools:targetApi="o" />

        <TextView
            android:id="@+id/SignInPasswordTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/password"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

        <EditText
            android:id="@+id/signInPasswordTextInput"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:autofillHints=""
            android:ems="10"
            android:hint="@string/password"
            android:inputType="textPassword"
            tools:targetApi="o" />

        <Button
            android:id="@+id/signInButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/sign_in" />

        <Button
            android:id="@+id/forgotPasswordButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/forgot_password" />

        <TextView
            android:id="@+id/signInErrorView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/error_view" />

        <Button
            android:id="@+id/verifyEmailAgainButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/email_verify_again" />

    </LinearLayout>

</LinearLayout>

Java Code

package com.amanthebreaker.firebaselogin;

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

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

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;

public class SignInActivity extends AppCompatActivity {

    private static final String TAG = "SignInActivity";
    public FirebaseAuth mAuth;
    EditText emailTextInput;
    EditText passwordTextInput;
    Button signInButton;
    Button forgotPasswordButton;
    Button sendVerifyMailAgainButton;
    TextView errorView;

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

        emailTextInput = findViewById(R.id.signInEmailTextInput);
        passwordTextInput = findViewById(R.id.signInPasswordTextInput);
        signInButton = findViewById(R.id.signInButton);
        forgotPasswordButton = findViewById(R.id.forgotPasswordButton);
        sendVerifyMailAgainButton = findViewById(R.id.verifyEmailAgainButton);
        errorView = findViewById(R.id.signInErrorView);

        sendVerifyMailAgainButton.setVisibility(View.INVISIBLE);

        mAuth = FirebaseAuth.getInstance();

        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (emailTextInput.getText().toString().contentEquals("")) {


                    errorView.setText("Email cant be empty");


                } else if (passwordTextInput.getText().toString().contentEquals("")) {

                    errorView.setText("Password cant be empty");

                } else {


                    mAuth.signInWithEmailAndPassword(emailTextInput.getText().toString(), passwordTextInput.getText().toString())
                            .addOnCompleteListener(SignInActivity.this, new OnCompleteListener<AuthResult>() {
                                @Override
                                public void onComplete(@NonNull Task<AuthResult> task) {
                                    if (task.isSuccessful()) {
                                        // Sign in success, update UI with the signed-in user's information
                                        Log.d(TAG, "signInWithEmail:success");

                                        FirebaseUser user = mAuth.getCurrentUser();

                                        if (user != null) {
                                            if (user.isEmailVerified()) {

                                                
                                                System.out.println("Email Verified : " + user.isEmailVerified());
                                                Intent HomeActivity = new Intent(SignInActivity.this, MainActivity.class);
                                                setResult(RESULT_OK, null);
                                                startActivity(HomeActivity);
                                                SignInActivity.this.finish();


                                            } else {

                                                sendVerifyMailAgainButton.setVisibility(View.VISIBLE);
                                                errorView.setText("Please Verify your EmailID and SignIn");

                                            }
                                        }

                                    } else {
                                        // If sign in fails, display a message to the user.
                                        Log.w(TAG, "signInWithEmail:failure", task.getException());
                                        Toast.makeText(SignInActivity.this, "Authentication failed.",
                                                Toast.LENGTH_SHORT).show();
                                        if (task.getException() != null) {
                                            errorView.setText(task.getException().getMessage());
                                        }

                                    }

                                }
                            });


                }


            }
        });


        forgotPasswordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent forgotPasswordActivity = new Intent(SignInActivity.this, ForgotPasswordActivity.class);
                startActivity(forgotPasswordActivity);
                SignInActivity.this.finish();

            }
        });


    }
}

Step 8) Welcome Screen Activity, After Login/SignIn, one would land to this dashboard page i.e Hello World Screen in our case

Dashboard Hello World Screen

XML Code

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="180dp"
        android:text="Hello World!"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/bLogout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Logout"
        android:onClick="LogoutActivity"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.183" />

</androidx.constraintlayout.widget.ConstraintLayout>

Java Code :

package com.amanthebreaker.firebaselogin;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity {

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

    public void LogoutActivity(View view) {
        FirebaseAuth.getInstance().signOut();
        Intent intent = new Intent(getApplicationContext(), WelcomeActivity.class);
        startActivity(intent);
    }
}

Step 9) Forgot Password Activity

XML Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:orientation="vertical"
    tools:context=".ForgotPasswordActivity">


    <TextView
        android:id="@+id/Title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#F1F1F1"
        android:text="@string/app_name"
        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/ForgotPasswordPageTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#F1F1F1"
        android:text="@string/forgot_password"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/fpEmailTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="@string/enterEmailId"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

    <EditText
        android:id="@+id/fpEmailTextInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:autofillHints=""
        android:ems="10"
        android:hint="@string/user_domain_com"
        android:inputType="textEmailAddress"
        tools:targetApi="o" />

    <Button
        android:id="@+id/resetPasswordButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/reset_password" />

</LinearLayout>

Java Code

package com.amanthebreaker.firebaselogin;

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

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;

public class ForgotPasswordActivity extends AppCompatActivity {


    private static final String TAG = "ForgotPasswordActivity";
    public FirebaseAuth mAuth;
    Button resetPasswordButton;
    EditText emailTextInput;

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


        emailTextInput = findViewById(R.id.fpEmailTextInput);
        resetPasswordButton = findViewById(R.id.resetPasswordButton);
        mAuth = FirebaseAuth.getInstance();


        resetPasswordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                mAuth.sendPasswordResetEmail(emailTextInput.getText().toString())
                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if (task.isSuccessful()) Log.d(TAG, "Email sent.");


                                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                                        ForgotPasswordActivity.this);

                                // set title
                                alertDialogBuilder.setTitle("Reset Password");

                                // set dialog message
                                alertDialogBuilder
                                        .setMessage("A Reset Password Link Is Sent To Your Registered EmailID")
                                        .setCancelable(false)
                                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {

                                                ForgotPasswordActivity.this.finish();
                                            }
                                        });

                                AlertDialog alertDialog = alertDialogBuilder.create();
                                alertDialog.show();


                            }
                        });


            }
        });


    }
}

Step 10) Create styles.xml in values folder with these resources

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#754ECC</color>
<resources>

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

Set color resources with these

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#754ECC</color>
    <color name="colorPrimaryDark">#341479</color>
    <color name="colorAccent">#FDD835</color>
</resources>

Here is the github repo of the project, Firebase Login. I have taken utmost care to avoid any bugs or errors in code, though there are some deprecated methods, which are fine for beginner to use, but I’d suggest readers, at least try, to find out these methods as well as fix with latest alternatives. If you find this task amazing, comment down below, otherwise you can leave a response.

Posts created 4

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top