Android working with Firebase – Signup and Login Auth

Today we will build a Signup and Login app using the Firebase Email & Password auth. Firebase is one of the largest account databases in the world. Firebase Authentication 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.

Firebase helps to develop for building high-quality apps, Firebase feature works independently, and they work even better together.

See products

Firebase – Signup and Login Auth

App Demo Screens

Android working with Firebase Authentication - Signup and Login All Screens

Now let’s get started to create a new project

Steps:-

  1. Start Android Studio.
  2. Create a New Project window that opens.
  3. Select Phone and Tablet.
  4. Select Empty Activity.
  5. Click Next.
  6. Enter the project name/App name.
  7. Set the company name as desired. In my case, I am using techpassappmaster.sign_upandlog_inwithfirebase
  8. Then select the project file location is and change it if desired.
  9. Select language java.
  10. Select Minimum SDK Android 4.3.
  11. Click “Finish.

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: – Your Android App and firebase project package name should be the same (mine is com.techpassappmaster.sign_upandlog_inwithfirebase).

  • Enabling Firebase Authentication

Go to your firebase project dashboard. Click > Authentication > Sign-in method and choose Email & Password and enable it.

Enabling Firebase Auth
Enabling Firebase Auth

 

  • Internet Permission

Open AndroidManifest.xml and add INTERNET permission for network requests.

   <uses-permission android:name="android.permission.INTERNET" />
  • Add Google Services classpath

 Open the build.gradle located in project’s and add Firebase google services 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 auth dependency and Apply Google Services Plugin

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

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.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'
    implementation 'com.google.android.material:material:1.0.0'

    //    firebase auth
    implementation 'com.google.firebase:firebase-auth:16.0.5'
}
apply plugin: 'com.google.gms.google-services'

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

  • Sign Up with Email & Password

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:gravity="center"
    android:orientation="vertical"
    tools:context=".SignUpActivity">


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

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="140dp"
        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:layout_marginBottom="22dp"
        android:text="New User Sign Up"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="26sp"
        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_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Email"
                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: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:inputType="textPassword" />
        </com.google.android.material.textfield.TextInputLayout>

        <Button
            android:id="@+id/button_register"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="22dp"
            android:background="#FFC400"
            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="20sp" />
    </LinearLayout>


</LinearLayout>

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

package com.techpassappmaster.sign_upandlog_inwithfirebase;

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 26-Jun-20.
 * www.techpassmaster.com
 */
public class SignUpActivity extends AppCompatActivity {

//    private static final Pattern PASSWORD_PATTERN = Pattern.compile("^" + "(?=.*[0-9])" + "(?=.*[a-z])" + "(?=.*[A-Z])" + "(?=.*[a-zA-Z])" + "(?=.*[@#$%^&+=])" + "(?=\\S+$)" + ".{4,}" + "$");

    private EditText txtemail, txtpass, txtcopass;
    private Button button_register;
    private TextView text_view_login;
    private FirebaseAuth mAuth;
    ProgressBar signUp_progress;

    String password, co_password, email;

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

        //        get all view id from XML
        txtemail = findViewById(R.id.edit_txt_email);
        txtpass = findViewById(R.id.edit_txt_pass);
        txtcopass = findViewById(R.id.edit_txt_coPass);
        signUp_progress = findViewById(R.id.signUp_progress);
        text_view_login = findViewById(R.id.text_view_login);
        button_register = findViewById(R.id.button_register);

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

        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 (!validateEmail() | !validatePassword())
                {
                    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()) {
                                //    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 validateEmail() {
        email = txtemail.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 = txtpass.getText().toString().trim();
        co_password = txtcopass.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;
        }
    }

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

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

        }
    }
}

3- Now, launcher SignupActivity. Run and test the signup.

Firebase Signup Screen

4- After the signup screen launch, enter the 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.

user created with the email id

  • Log In with Email & 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="match_parent"
        android:layout_height="140dp"
        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:layout_marginBottom="22dp"
        android:text="Login Account"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="26sp"
        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" />
        </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" />
        </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="#651FFF"
            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="#FFC400"
            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.techpassappmaster.sign_upandlog_inwithfirebase;

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 26-Jun-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

  • 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"
    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="140dp"
        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/black"
        android:textSize="26sp"
        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" />


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

        <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>

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

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

        <Button
            android:id="@+id/button_resetPassword"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="22dp"
            android:background="#FFC400"
            android:text="Send Me Link"
            android:textAllCaps="false"
            android:textColor="#fff"
            android:textSize="20sp" />

    </LinearLayout>
</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.techpassappmaster.sign_upandlog_inwithfirebase;

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 26-Jun-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_SHORT).show();
                                    Intent intent = new Intent(ForgotPasswordActivity.this, LoginActivity.class);
                                    startActivity(intent);
                                    finish();
                                } else {
                                    Toast.makeText(ForgotPasswordActivity.this, "Something error", Toast.LENGTH_SHORT).show();
                                }

                            }
                        });
            }
        });

    }
}

3- Now, launch ForgotPasswordActivity. Run and test the reset password.

Firebase- Reset Password Screen

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

Firebase - Reset 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="#02C164"
        android:textSize="26sp"
        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.techpassappmaster.sign_upandlog_inwithfirebase;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
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 26-Jun-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

Congrats! You’ve now completed your signup and login app with Firebase. 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 2 Comments

  1. Avatar
    Ingrid Bell

    I’m extremely impressed with your writing skills as well as with
    the layout on your blog. Is this a paid theme or
    did you modify it yourself? Either way keep up the excellent quality writing, it is rare
    to see a nice blog like this one these days.

Leave a Reply