Firebase Authentication with Custom User Fields in Android

Firebase helps to develop for building high-quality apps, Firebase feature works independently, and they work even better together and it is one of the largest account databases in the world. Firebase provides an end-to-end identity solution, supporting email and password accounts, phone auth, and Google, Twitter, Facebook, and GitHub login, and more and It’s very secure authentication systems.

Read More:- Android Working With Firebase – Signup And Login Auth

Let’s build a user Authentication with custom fields in Android using the Firebase. Firebase provides a full set of authentication options away from the inside and it automatically stores user’s credentials securely with the help of bcrypt.

Firebase Authentication with custom user fields in Android

App Demo Screens

Now let’s get started to create a new project

  1. Open android studio.
  2. Create a new project.
  3. Filling the project details.

After successfully created the project. Add project with Firebase.

If you don’t know how to add a project with Firebase. Check our previous post Getting Started With Firebase On Android (2020).

Note: – Use the same package name which you gave in the firebase console. In my case, I am using the same (com.techpassmaster.firebaseauthwithcustomfields) and Paste the google-services.json file to your project’s app folder. This step is very important.

  • Enabling Firebase Authentication

  • Create & Enabling Realtime Database

  • Navigate to the Database section of the Firebase console. You’ll be prompted to select an existing Firebase project. Follow the database creation workflow.

Select a starting mode for your Firebase Security Rules:

  • Test mode

Good for getting started with the mobile and web client libraries, but allows anyone to read and overwrite your data. After testing, make sure to review the Understand Firebase Realtime Database Rules section.

  • Locked mode

Denies all reads and writes from mobile and web clients. Your authenticated application servers can still access your database.

  • Click Enable.

Enabling Realtime Database

  • Internet Permission

Goto your android studio project. Open AndroidManifest.xml and add INTERNET permission for network requests.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  • Open the build.gradle located in the project’s home directory and add firebase dependency.
dependencies {
        classpath 'com.android.tools.build:gradle:4.0.0'
        classpath 'com.google.gms:google-services:4.2.0'
        
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
  • Add firebase authentication or Realtime Database dependency, Add Apply Google Services Plugin

Open app/build.gradle and add firebase auth and realtime database dependency, add apply plugin: ‘com.google.gms.google-services’ at the bottom of the file

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

//    android material design
    implementation 'com.google.android.material:material:1.1.0'

    //    firebase auth
    implementation 'com.google.firebase:firebase-auth:19.3.1'

//    firebase realtime database
    implementation 'com.google.firebase:firebase-database:19.3.1'
}
apply plugin: 'com.google.gms.google-services'

Now we have added all the required dependencies. Let’s start to make the custom user fields sign-up screen.

  • Create a new Java class

Create a class named UserData.java and declare Fullname, Username, Emailid, Gender generates the constructor methods to each variable.

package com.techpassmaster.firebaseauthwithcustomfields;

/**
 * Created by Techpass Master on 01-Jul-20.
 * www.techpassmaster.com
 */
public class UserData {

    public String Fullname,Username,EmailId,Gender;

    public UserData()
    {

    }
    public UserData(String fullname, String username, String emailId, String gender) {
        Fullname = fullname;
        Username = username;
        EmailId = emailId;
        Gender = gender;
    }
}
  • Now create custom user fields sign-up screen

1- Create an activity named SignupActivity and add the following code to the layout file activity_signup.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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16sp"
    tools:context=".SignUpActivity">


    <ProgressBar
        android:id="@+id/signUp_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="gone" />

    <ImageView
        android:layout_width="300dp"
        android:layout_gravity="center"
        android:layout_height="100dp"
        android:background="@drawable/firebase_logo" />


    <TextView
        android:id="@+id/login_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="New User Sign Up"
        android:textAlignment="center"
        android:textColor="@android:color/holo_blue_dark"
        android:textSize="22sp"
        android:textStyle="bold" />

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/edit_txt_Fullname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Full Name"
            android:textSize="16sp"
            android:inputType="textWebEmailAddress" />

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/edit_txt_Username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="User Name"
            android:textSize="16sp"
            android:inputType="textWebEmailAddress" />

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/edit_txt_Email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email"
            android:textSize="16sp"
            android:inputType="textWebEmailAddress" />

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:passwordToggleEnabled="true">

        <EditText
            android:id="@+id/edit_txt_Pass"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Password"
            android:textSize="16sp"
            android:inputType="textPassword" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:passwordToggleEnabled="true">

        <EditText
            android:id="@+id/edit_txt_CoPass"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Co-Password"
            android:textSize="16sp"
            android:inputType="textPassword" />
    </com.google.android.material.textfield.TextInputLayout>


    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Gender"
            android:textColor="@android:color/black"
            android:textSize="16sp"
            android:textStyle="bold" />

        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:text="Male" />

        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:text="Female" />
    </RadioGroup>

    <Button
        android:id="@+id/button_register"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:background="#651FFF"
        android:text="Sign Up"
        android:textAllCaps="false"
        android:textColor="#fff"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/text_view_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Already have an account.\nLogin Here"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="16sp" />

</LinearLayout>

2- Open SignupActivity.java and add the following. Firebase gives the createUserWithEmailAndPassword() method and set value for custom user fields auth.

package com.techpassmaster.firebaseauthwithcustomfields;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
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.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

/**
 * Created by Techpass Master on 01-Jul-20.
 * www.techpassmaster.com
 */
public class SignUpActivity extends AppCompatActivity {

    private EditText edit_txt_Fullname, edit_txt_Username, edit_txt_Email, edit_txt_Pass, edit_txt_CoPass;
    private RadioButton radioMale, radioFemale;
    private Button button_register;
    private TextView text_view_login;
    ProgressBar signUp_progress;

    private DatabaseReference databaseReference;
    private FirebaseDatabase firebaseDatabase;
    private FirebaseAuth mAuth;


    String fullname, username, email, password, co_password;

    String gender = "";

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

        //        get all view id from XML

        signUp_progress = findViewById(R.id.signUp_progress);
        edit_txt_Fullname = findViewById(R.id.edit_txt_Fullname);
        edit_txt_Username = findViewById(R.id.edit_txt_Username);
        edit_txt_Email = findViewById(R.id.edit_txt_Email);
        edit_txt_Pass = findViewById(R.id.edit_txt_Pass);
        edit_txt_CoPass = findViewById(R.id.edit_txt_CoPass);
        radioMale = findViewById(R.id.radioMale);
        radioFemale = findViewById(R.id.radioFemale);
        text_view_login = findViewById(R.id.text_view_login);
        button_register = findViewById(R.id.button_register);

        //        Get Firebase auth instance
        mAuth = FirebaseAuth.getInstance();
        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReference = firebaseDatabase.getReference("UserData");

        text_view_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(intent);
            }
        });

        //        handle user SignUp button
        button_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!validateFullname() | !validateUsername() | !validateEmail() | !validatePassword() | checkUserGender()) {
                    return;
                }

                if (password.equals(co_password)) {

                    //    progressbar VISIBLE
                    signUp_progress.setVisibility(View.VISIBLE);
                    mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener
                            (new OnCompleteListener<AuthResult>() {
                                @Override
                                public void onComplete(@NonNull Task<AuthResult> task) {

                                    if (task.isSuccessful()) {

                                        UserData data = new UserData(fullname, username, email, gender);

                                        FirebaseDatabase.getInstance().getReference("UserData")
                                                .child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(data).
                                                addOnCompleteListener(new OnCompleteListener<Void>() {
                                                    @Override
                                                    public void onComplete(@NonNull Task<Void> task) {

                                                        //    progressbar GONE
                                                        signUp_progress.setVisibility(View.GONE);

                                                        Toast.makeText(SignUpActivity.this, "Successful Registered", Toast.LENGTH_SHORT).show();
                                                        Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
                                                        startActivity(intent);
                                                        finish();
                                                    }
                                                });


                                    } else {
                                        //    progressbar GONE
                                        signUp_progress.setVisibility(View.GONE);
                                        Toast.makeText(SignUpActivity.this, "Check Email id or Password", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                } else {
                    Toast.makeText(SignUpActivity.this, "Password didn't match", Toast.LENGTH_SHORT).show();
                }
            }
        });


    }

    private boolean validateFullname() {
        fullname = edit_txt_Fullname.getText().toString().trim();
        if (TextUtils.isEmpty(fullname)) {
            Toast.makeText(SignUpActivity.this, "Enter Your Full Name", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            return true;
        }
    }

    private boolean validateUsername() {
        username = edit_txt_Username.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(SignUpActivity.this, "Enter Your User Name", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            return true;
        }
    }

    private boolean validateEmail() {
        email = edit_txt_Email.getText().toString().trim();
        if (TextUtils.isEmpty(email)) {
            Toast.makeText(SignUpActivity.this, "Enter Your Email", Toast.LENGTH_SHORT).show();
            return false;
        } else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            Toast.makeText(SignUpActivity.this, "Please enter valid Email", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            return true;
        }
    }

    private boolean validatePassword() {
        password = edit_txt_Pass.getText().toString().trim();
        co_password = edit_txt_CoPass.getText().toString().toLowerCase();

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(SignUpActivity.this, "Enter Your Password", Toast.LENGTH_SHORT).show();
            return false;
        } else if (TextUtils.isEmpty(co_password)) {
            Toast.makeText(SignUpActivity.this, "Enter Your Co-Password", Toast.LENGTH_SHORT).show();
            return false;
        } else if (password.length() <= 6) {
            Toast.makeText(SignUpActivity.this, "Password is Very Short", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            return true;
        }
    }

    private boolean checkUserGender() {

        if (radioMale.isChecked()) {
            gender = "Male";
            return false;

        }
        if (radioFemale.isChecked()) {
            gender = "Female";
            return false;

        } else {
            Toast.makeText(SignUpActivity.this, "Select Your Gender", Toast.LENGTH_SHORT).show();
            return true;
        }
    }


    //    if the user already logged in then it will automatically send on Dashboard/MainActivity activity.
    @Override
    public void onStart() {
        super.onStart();

        if (FirebaseAuth.getInstance().getCurrentUser() != null) {
            Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
            startActivity(intent);

        }
    }
}

3- Run and test the SignupActivity.

Firebase- Custom user signup screen
Firebase- Custom user signup screen

 

4- After the signup screen launch, enter the Full Name, User Name, Email id, and password. If you successfully login to Firebase you can see the user-created with the email id you have given the android app and as well as custom user fields data saved in Realtime Database.

user created with the email id
User-created with the email id and user UID
Custom fields user data
  • Log In with Email ID & Password

Now we’ll create a login screen to check the credentials user you have created on sign up screen.

1- Create new activity named LoginActivity and add the below code to its layout file activity_login.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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".LoginActivity">


    <ProgressBar
        android:id="@+id/login_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone" />

    <ImageView
        android:layout_width="300dp"
        android:layout_gravity="center"
        android:layout_height="100dp"
        android:background="@drawable/firebase_logo" />


    <TextView
        android:id="@+id/login_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="22dp"
        android:layout_marginTop="20dp"
        android:text="Login Account"
        android:textAlignment="center"
        android:textColor="@android:color/holo_blue_dark"
        android:textSize="22sp"
        android:textStyle="bold" />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="20dp">

        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/edit_txt_login_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Email"
                android:inputType="textWebEmailAddress"
                android:textSize="16sp" />
        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:passwordToggleEnabled="true">

            <EditText
                android:id="@+id/edit_txt_login_pass"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Password"
                android:inputType="textPassword"
                android:textSize="16sp" />
        </com.google.android.material.textfield.TextInputLayout>

        <TextView
            android:id="@+id/text_view_forget_password"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:paddingTop="8dp"
            android:text="Forgot Password ?"
            android:textColor="#FF9100"
            android:textSize="16sp" />

        <Button
            android:id="@+id/button_login"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="22dp"
            android:background="#651FFF"
            android:text="Login"
            android:textAllCaps="false"
            android:textColor="#fff"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/text_view_signup"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Don't have an account.\nSign Up Here"
            android:textAlignment="center"
            android:textColor="@android:color/holo_green_dark"
            android:textSize="20sp" />

    </LinearLayout>

</LinearLayout>

2- Open LoginActivity.java and add the below code. Firebase gives signInWithEmailAndPassword()method to sign in the user.

package com.techpassmaster.firebaseauthwithcustomfields;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
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.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
/**
 * Created by Techpass Master on 01-Jul-20.
 * www.techpassmaster.com
 */
public class LoginActivity extends AppCompatActivity {

    private EditText txtemail, txtpassoword;
    private Button login_btn;
    private TextView text_view_signup, forgot_password;

    ProgressBar login_progress;
    FirebaseAuth mAuth;

    String loginemail, loginpassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //        get all view id from XML
        txtemail = findViewById(R.id.edit_txt_login_email);
        txtpassoword = findViewById(R.id.edit_txt_login_pass);
        forgot_password = findViewById(R.id.text_view_forget_password);
        login_progress = findViewById(R.id.login_progress);
        text_view_signup = findViewById(R.id.text_view_signup);
        login_btn = findViewById(R.id.button_login);

        //        Get Firebase auth instance
        mAuth = FirebaseAuth.getInstance();


        //        handle login button
        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!validateEmail() | !validatePassword()) {
                    return;
                }

                //    progressbar VISIBLE
                login_progress.setVisibility(View.VISIBLE);

                mAuth.signInWithEmailAndPassword(loginemail, loginpassword).
                        addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                //    progressbar GONE
                                login_progress.setVisibility(View.GONE);
                                if (task.isSuccessful()) {
                                    Toast.makeText(LoginActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                } else {

                                    //    progressbar GONE
                                    login_progress.setVisibility(View.GONE);
                                    Toast.makeText(LoginActivity.this, "Login Failed", Toast.LENGTH_SHORT).show();
                                }
                            }

                        });

            }

        });

        //        handle forgot button
        forgot_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), ForgotPasswordActivity.class);
                startActivity(intent);
            }
        });

        //        handle signUp textview
        text_view_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
                startActivity(intent);
            }
        });

    }

    private boolean validateEmail() {
        loginemail = txtemail.getText().toString().trim();
        if (TextUtils.isEmpty(loginemail)) {
            Toast.makeText(LoginActivity.this, "Enter Your Email", Toast.LENGTH_SHORT).show();
            return false;
        } else if (!Patterns.EMAIL_ADDRESS.matcher(loginemail).matches()) {
            Toast.makeText(LoginActivity.this, "Please enter valid Email", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            return true;
        }
    }

    private boolean validatePassword() {
        loginpassword = txtpassoword.getText().toString().trim();

        if (TextUtils.isEmpty(loginpassword)) {
            Toast.makeText(LoginActivity.this, "Enter Your Password", Toast.LENGTH_SHORT).show();
            return false;

        } else {
            return true;
        }
    }
}

 3- Now, launcher LoginActivity.java. Run the project and log in with the credentials which you used while signing up.

Firebase- Login screen
Firebase- Login screen
  • Forgot Password – Send Reset Password Link on Email

Firebase provides the feature to reset the password, When you forget your auth password, then you have the need to your auth email, the Firebase sends a reset password URL link on your email account. Let’s see the code of it.

1- Create another activity named ForgotPasswordActivity.java and add the below code its layout file activity_forgot_password.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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="22dp"
    tools:context=".ForgotPasswordActivity">

    <ProgressBar
        android:id="@+id/resetPassword_progress"
        android:layout_width="wrap_content"
        android:visibility="gone"
        android:layout_height="wrap_content"/>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:layout_marginBottom="22dp"
        android:background="@drawable/firebase_logo" />

    <TextView
        android:id="@+id/login_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Reset Password ?"
        android:textAlignment="center"
        android:layout_marginBottom="22dp"
        android:textColor="@android:color/holo_blue_dark"
        android:textSize="22sp"
        android:textStyle="bold" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Enter your email to received reset link"
        android:textAlignment="center"
        android:layout_marginBottom="22dp"
        android:textColor="@android:color/black"
        android:textSize="20sp" />



    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/edit_txt_resetEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email"
            android:inputType="textWebEmailAddress" />

    </com.google.android.material.textfield.TextInputLayout>


    <Button
        android:id="@+id/button_resetPassword"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:background="#651FFF"
        android:text="Send"
        android:textAllCaps="false"
        android:textColor="#fff"
        android:textSize="20sp" />


</LinearLayout>

2- Open ForgotPasswordActivity.java. You can use the sendPasswordResetEmail() method to send the password reset URL link on your email, follow the below code.

package com.techpassmaster.firebaseauthwithcustomfields;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
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;
/**
 * Created by Techpass Master on 01-Jul-20.
 * www.techpassmaster.com
 */
public class ForgotPasswordActivity extends AppCompatActivity {

    private EditText edit_txt_resetEmail;
    private Button button_resetPassword;
    private ProgressBar resetPassword_progress;
    FirebaseAuth firebaseAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgot_password);
        //        get all view id from XML
        edit_txt_resetEmail = findViewById(R.id.edit_txt_resetEmail);
        button_resetPassword = findViewById(R.id.button_resetPassword);
        resetPassword_progress = findViewById(R.id.resetPassword_progress);

        //        Get Firebase auth instance
        firebaseAuth = FirebaseAuth.getInstance();


        button_resetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                resetPassword_progress.setVisibility(View.VISIBLE);

                firebaseAuth.sendPasswordResetEmail(edit_txt_resetEmail.getText().toString())
                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                resetPassword_progress.setVisibility(View.GONE);
                                if (task.isSuccessful()) {
                                    Toast.makeText(ForgotPasswordActivity.this, "Password reset link sent to your Email", Toast.LENGTH_LONG).show();
                                    Intent intent = new Intent(ForgotPasswordActivity.this, LoginActivity.class);
                                    startActivity(intent);
                                    finish();
                                } else {
                                    Toast.makeText(ForgotPasswordActivity.this, "Something error", Toast.LENGTH_SHORT).show();
                                }

                            }
                        });
            }
        });


    }
}

3- Run and test the reset password.

Firebase- Reset forgot password
Firebase- Reset forgot password

This is your reset password URL. Click to change the new password.

  • Logout

1- After the successful login, the user will be switch to the dashboard or main activity, for that create a new activity named MainActivity.

Add the below code its layout file activity_main.xml

<?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:gravity="center"
    android:orientation="vertical"
    android:padding="16sp"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/txt_userEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="User Email"
        android:textAlignment="center"
        android:textColor="#2979FF"
        android:textSize="22sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btn_userlogout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:background="#651FFF"
        android:text="Logout"
        android:textColor="#ffff"
        android:textSize="18sp"
        android:textStyle="bold" />
</LinearLayout>

2- Open MainActivity.java. You can use the signOut() method for the logout credentials user account and add the following code to MainActivity.java.

package com.techpassmaster.firebaseauthwithcustomfields;

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

import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

/**
 * Created by Techpass Master on 01-Jul-20.
 * www.techpassmaster.com
 */
public class MainActivity extends AppCompatActivity {

    private TextView txt_userEmail;
    private Button btn_userlogout;

    FirebaseUser firebaseUser;
    FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //        get all view id from XML
        txt_userEmail = findViewById(R.id.txt_userEmail);
        btn_userlogout = findViewById(R.id.btn_userlogout);

        //        Get Firebase auth instance
        mAuth = FirebaseAuth.getInstance();
        firebaseUser = mAuth.getCurrentUser();

        txt_userEmail.setText(firebaseUser.getEmail());


//        handle Logout button
        btn_userlogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAuth.signOut();
                Toast.makeText(MainActivity.this, "Logout Successful ", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finishAffinity();
    }
}

3- Run and test the Logout.

Firebase- Logout Screen
Firebase- Logout Screen

Congrats! You’ve now completed Firebase Authentication With Custom User Fields. Check the demo app link given below. 

I hope you liked the post. If you have any questions regarding this post. Feel free to comment and share the post with your friends.

Happy Learning!!!  🙂

This Post Has 11 Comments

  1. Avatar
    Hardy

    Hello I’m following your tutorial about this, but I got error when I launch the Register page

  2. Avatar
    Yan Ouedraogo

    Thank you very much ! Your tutorial helped me a lot. Very complete !

  3. Avatar
    sikis izle

    Excellent post. Keep posting such kind of information on your site. Kelila Lief Tseng

  4. Avatar
    erotik film izle

    Please visit the web pages we comply with, such as this a single, because it represents our picks in the web. Corrie Bailie Armillas

  5. Avatar
    erotik film izle

    I have recently started a site, the information you offer on this site has helped me greatly. Thank you for all of your time & work. Fey Ronnie Scevor

  6. Avatar
    Theresa

    I like and follow your site, thanks

Leave a Reply