Implementing Firebase Auth in Android App | Sign-in Sign-up with Email

0
35
Firebase Auth Android Feature image - firebasetutorials.com
Feature Image by: pexels.com

We are going to implement one of the most vital features of any app, the Sign-in Sign-up feature. We are not going for the custom servers, we are not going to write a ton of code to do that. We are just going to implement the Firebase Auth in our Android App it performs the complete Sign-In Sign-Up using the email address and password. 

If you want to cut out more than half of backend development of your app then Firebase is a perfect product for you. Plus it is a Google product, so we can count on it.

Here is what you will be learning through this tutorial:

Without any further due, let’s get straight into development.

Here is the content table that we are going to follow:

Connecting Firebase and implementing Firebase Auth

Recommended: Firebase Remote Config – Complete Android Tutorials (with Sample App)

So, first of all, we need to connect our app to Firebase.
There are two methods to do that,

  • The Firebase Assistant – is just like an Android Studio plugin which assists us to implement the Firebase products
  • The Manual Method – where we do all the stuff yourself like adding the libraries, downloading the JSON file, etc.

We are sticking with the first one, as it is quite simple and hassle-free. All we need to do is click on Firebase under Tools menu of Android Studio [I am using Windows]

Now a pane will appear from the right side, expand the Authentication one, and click on “The email and password authentication

NOTE: We are just going to cover the signup and sign in with email and password only, I was thinking of creating a series of further doing this. If you want me to do then let me know in comments.

Now you see a bunch of steps in that pane. Just go through the first two to connect the Firebase and implement Firebase Authentication to your app.

  1. Click “Connect to Firebase

Make sure you are signed in with your Google account in Android Studio. If you are signed in then it will ask to either create a new project or choose an existing one. You can do as it suits you, I am choosing the existing project, and hit the “Connect to Firebase Button”. Now an app will be created in that project, JSON file will be added to Android Studio, libraries will be added and gradle will start to sync. If there was no Firebase Assistant we have to do all of it manually. Once the gradle sync is complete, it is time for the next step.

   2. Click “Add Firebase Authentication to your app” button

A dialog will appear prompting that these changes are going to be made. Hit the “Accept Changes” button and let it do its stuff.

Here is the visual representation:

Connecting Android app to firebase
Connecting Firebase and implementing Firebase Auth in Android App

When everything is completed safely. It should look like this:

Firebase Auth implemented
Firebase Auth Implemented

Setting Firebase Console Up

Now the Firebase is connected and Firebase Authentication is successfully implemented in our app.

As we are going to implement the Sign in and sign up with email and password only, so we need to enable it in Firebase Console settings.

Here are the steps:

  1. Open Firebase Console and select the project where your app resides.
  2. Select the Authentication option in the left pane, under Develop category.
  3. Select the Sign In method tab.
  4. Under Sign In Provides list, edit Email/Password and enable it.
  5. Hit the Save button

Here is the visual presentation:

Setting up Firebase Console for Firebase Auth
Setting up Firebase console for Firebase Auth with email address and password

The App Workflow

Okay great, settings are complete it is time to write the code.

But before, please understand the workflow of this app:

Firebase Auth Android App workflo
Firebase Auth Android App workflow

This may look complicated but it not really complicated.

The only main thing is when the app starts, MainActivity will be launched and before it set any content to the screen, it will be checked if the user is logged in or not?

If logged in, then set content to the MainAcitvity and show the user email address.

If not logged in, then start the SignInActivity and finish the MainActivity. That’s all.

 

Note: I am not going to build the UI, it will make the tutorial a lot longer and boring, If you want then comment below and a new tutorial regarding it will be up soon.


Writing Code for Firebase Auth


MainActivity

Okay so starting with MainActivity. Here are the objectives:

  1. Check if the user logged in
  2. Start SignInAcitivty if not
  3. Show the user email if it is
  4.      Logout user

Check if the user logged in

To perform the first step, we need an instance of FirebaseAuth. We can get it as:

private FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance();

Now through this instance, we can check if the user logged in or not.

We will get the current user and check if it null or not. Null means no user logged in and we need to start the SignInActivity.

    FirebaseUser currentUser = mAuth.getCurrentUser();
    if (currentUser == null) {
//No one signed in
      startActivity(new Intent(this, SignInActivity.class));
      this.finish();
    }

Show email if the user logged in

Otherwise, we will just get the email address of the current user and show it. The Firebase Auth provides a function getEmail(), that we can call on currentUser object to get the email address!

else{
//User logged in
      mTvEmail.setText(currentUser.getEmail());
    }

Logout user

User stays logged in until someone performs the log out manually, clears the app data or the user account is disabled/deleted in Firebase Console. 

We need to show a button to log out the user. When pressed it needs to call signOut() method on FirebaseAuth instance variable. This method/function will perform the signOut mechanism. 

After calling the signOut() method, we need to start the SignInActivity so that the new user can perform the sign in. And finish the MainAcivity so that when the back is pressed from SignInActivity, the app should exit instead of showing the MainActivity again and causing some problems. 

mTvLogout.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View view) {
        mAuth.signOut();
        startActivity(new Intent(MainActivity.this, SignInActivity.class));
        MainActivity.this.finish();
 
      }
    });

 

That’s all for the MainActivity.

Here is the complete code for MainActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {

  private FirebaseAuth mAuth;
  private TextView mTvEmail, mTvLogout;

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

    mAuth = FirebaseAuth.getInstance();


    mTvLogout = findViewById(R.id.txtBtnLogout);
    mTvEmail = findViewById(R.id.tvEmail);


    FirebaseUser currentUser = mAuth.getCurrentUser();
    if (currentUser == null) {
//No one signed in
      startActivity(new Intent(this, SignInActivity.class));
      this.finish();
    }else{
//User logged in
      mTvEmail.setText(currentUser.getEmail());
    }



    mTvLogout.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View view) {
        mAuth.signOut();
        startActivity(new Intent(MainActivity.this, SignInActivity.class));
        MainActivity.this.finish();

      }
    });


  }
}

SignInActivity

Recommended: Send push notification in Firebase using Android

Objectives of this activity:

  1. Get email and password from the user,
  2. Authenticate user from Firebase
  3. Keep the user updated
  4. Start MainActivity if login success
  5. Show appropriate message if fails

Getting email and password from the user

Getting email and password from the user is quite easy, just use the EditText in XML and get the text in java using .getText() method.

Authenticate user from Firebase

To Authenticate the user from Firebase, we need Firebase an Instance of FirebaseAuth.

private FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance();

Firebase provides a method named signInWithEmailAndPassword(), we need to call that method on Firebase Auth instance variable to perform sign-in with email and password.

As this method returns a task, so we can check if it was completed or not. If it was successful then start the MainActivity and finish the SignInActivity.

If it didn’t then show the message in a SnackBar

FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
        firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(
            new OnCompleteListener<AuthResult>() {
              @Override
              public void onComplete(@NonNull Task<AuthResult> task) {

                if (task.isSuccessful()) {
                  startActivity(new Intent(SignInActivity.this, MainActivity.class));
                  finish();
                } else {
                  Snackbar
                      .make(root, task.getException().getLocalizedMessage(), Snackbar.LENGTH_LONG)
                      .show();
                }
              }
            });

Keep user updated

To keep the user updated. I am going to use a RelativeLayout which spreads across the whole screen and top of that, there is a ProgressBar. So I am setting both to invisible as the Activity starts. And will show them as user click the login

Button and will hide when there is any response from the task, either successful or not, I need to take off these layouts.

Start MainActivity if login completes

In our sign SignInWithEmailAndPassword() method we already checked if the task is successful or not. So we can start the MainActivity right from there

Show message if log in fails

To do so, we are using the SnackBar to show the error message we get from the task object.

Here is the complete SignInActivity code:

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
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;

public class SignInActivity extends AppCompatActivity {

  private TextView mBtnSignIn;
  private EditText mEtEmail, mEtPassword;
  private RelativeLayout root, mRlSignUp, mRlFadingLayout;
  private ProgressBar mProgressBar;

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

    mBtnSignIn = findViewById(R.id.txtBtnLogin);
    mEtPassword = findViewById(R.id.etPass);
    mEtEmail = findViewById(R.id.etEmail);
    root = findViewById(R.id.rlSigInRoot);
    mRlSignUp = findViewById(R.id.rlSignUp);
    mRlFadingLayout = findViewById(R.id.rlFadingLayout);
    mProgressBar = findViewById(R.id.progressBar);

    mRlSignUp.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View view) {
        startActivity(new Intent(SignInActivity.this, SignUpActivity.class));
        finish();
      }
    });

    mBtnSignIn.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View view) {
     
        String email = mEtEmail.getText().toString();
        String password = mEtPassword.getText().toString();

        FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
        firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(
            new OnCompleteListener<AuthResult>() {
              @Override
              public void onComplete(@NonNull Task<AuthResult> task) {

                mProgressBar.setVisibility(View.INVISIBLE);
                mRlFadingLayout.setVisibility(View.INVISIBLE);

                if (task.isSuccessful()) {
                  startActivity(new Intent(SignInActivity.this, MainActivity.class));
                  finish();
                } else {
                  Snackbar
                      .make(root, task.getException().getLocalizedMessage(), Snackbar.LENGTH_LONG)
                      .show();
                }
              }
            });

      }
    });

  }
}

SignUpActivity

As you can see from the workflow diagram, we are getting email address, password and confirm password form user.

The password and confirm password are needed to be matched before proceeding further.

We are not doing any validation to the email address at this point, it means the user can enter any email address and Firebase will accept it as long as it is properly formatted. 

Firebase does provide a mechanism to validate the email by sending an email to that address and user has to accept that. We will cover that in some upcoming tutorial.

Objectives of SignUpActivity:

  1. Get the email address and password from the user.
  2. Check if both password match
  3. Create a new account with email address and password
  4. If fails, show the appropriate message.
  5. If done, start the MainActivity.
  6. Keep the user updated.

Get the email and password from the user

Getting the email address and password from the user is quite easy. Just show to EditText and get the text from user accordingly. I am not showing that code here. I hope you know how to do that.

PS: You are getting the complete activity code if you don’t really know.

Check if both passwords match

This is also quite simple. I guess you know how to compare two strings. So I am leaving this too!

PS: You are getting the complete activity code if you don’t really know.

Create a new account with email address and password

Starting with creating an account. Firebase Auth provides us a method named createUserWithEmailAndPassword(String email, String password).

We can pass the email address and password to create an account. This method returns a Task object which we can use to check if the process was successful or not.

To call this method we need FirebaseAuth instance:

private FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance();

Now call that method and pass the details we got from the user.

If the process ends successfully then start the MainActivity and exit current.

If not then show the appropriate message again using SnackBar

firebaseAuth.createUserWithEmailAndPassword(email, pass).addOnCompleteListener(
              new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                  if (task.isSuccessful()) {
                    startActivity(new Intent(SignUpActivity.this, MainActivity.class));
                    finish();
                  } else {
                    Snackbar.make(mRlRoot, task.getException().getMessage(), Snackbar.LENGTH_LONG)
                        .show();
                  }

                }
              });

 

Yuffie, there was a hell lot to do.

But stills we need to do the final adjustments like showing a ProgressBar so that user knows something is going on. Again, it is done as earlier.

So here is the complete SingUpActivity.java code:

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
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;

public class SignUpActivity extends AppCompatActivity {

  private EditText mEtEmail, mEtPassword, mEtConfirmPassword;
  private TextView mTvSignUp;
  private RelativeLayout mRlRoot, mRlFading;
  private ProgressBar mProgressBar;

  private static final String TAG = "SignUpActivity";

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

    mEtEmail = findViewById(R.id.etEmail);
    mEtPassword = findViewById(R.id.etPass);
    mEtConfirmPassword = findViewById(R.id.etPassConfirm);

    mTvSignUp = findViewById(R.id.txtBtnSignUp);

    mRlFading = findViewById(R.id.rlFadingLayout);
    mRlRoot = findViewById(R.id.rlRoot);

    mProgressBar  = findViewById(R.id.progressBar);

    mTvSignUp.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View view) {
        String pass = mEtPassword.getText().toString();
        String confirmPass = mEtConfirmPassword.getText().toString();
        String email = mEtEmail.getText().toString();



        if (!pass.equals(confirmPass)) {
          Snackbar.make(mRlRoot, "Password Doesn't match", Snackbar.LENGTH_LONG).show();
        } else {
          mProgressBar.setVisibility(View.VISIBLE);
          mRlFading.setVisibility(View.VISIBLE);
          FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
          firebaseAuth.createUserWithEmailAndPassword(email, pass).addOnCompleteListener(
              new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                  if (task.isSuccessful()) {
                    Toast.makeText(SignUpActivity.this, "SignUp Complete", Toast.LENGTH_SHORT)
                        .show();
                    startActivity(new Intent(SignUpActivity.this, MainActivity.class));
                    finish();
                  } else {
                    Snackbar.make(mRlRoot, task.getException().getMessage(), Snackbar.LENGTH_LONG)
                        .show();
                  }

                }
              });
        }


      }
    });


  }
}

Okay, at this point I assume that you know how to perform the SignIn and SignUp in your Android app using Firebase Auth. You can also read my previous tutorials here:

How to develop apps 5X quickly with Firebase