Firebase

FirebaseUI for Authentication with Email

Pinterest LinkedIn Tumblr

Welcome guys, In this post I’ll show you sign in with email with FirebaseUI. Firebase provides many ways for authentication. Here, I’ll explain FirebaseUI to login using email and password. so Let’s get started.

Why should use FirebaseUI for Authentication?

FirebaseUI is an open-source library, you can also customize it because of open source. It eliminates boilerplate code and promotes android best practices with user experiences and security. FirebaseUI is all enabled single tap to enable and returning users also.

Connect your app to firebase

Let’s open an android studio and create a new android project with the empty activity template. I’m taking the package name here com.firebaseauthenticationuiexample . Once the project created, connect your app to the firebase. Please follow this article for creating a project on firebase console.

Add a new classpath in project-level build.gradle

Open the project-level build.gradle and add the below line.

//Add this line
classpath 'com.google.gms:google-services:4.3.2'
Add new plugin in app-level build.gradle

Open the app-level build.gradle and google services plugin by adding this line

// add this line
apply plugin: 'com.google.gms.google-services'
Add firebase UI auth dependency in same app level gradle file

Firebase UI auth library needs to perform a firebase auth with email.

implementation 'com.firebaseui:firebase-ui-auth:4.3.1'

After adding sync the project and make sure everything is working fine.

Enable email and password authentication on firebase console.

Go to the firebase console and enable email password authentication. So go to the Authentication option in the left panel. Once you open on authentication go to Sign In method and enable email password.

Create a LoginActvitiy

I’m creating a new activity with a layout file. Here I’m adding a button for initiating login just for demonstration purposes. Let’s go to the layout file and add SignIn button just like below

<?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=".LoginActivity"
    >
  <Button
      android:id="@+id/buttonSignIn"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="SignIn with Email"
      android:textAllCaps="false"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      />

</androidx.constraintlayout.widget.ConstraintLayout>
Let’s go to LoginActivity.

In the LoginActivity, before initiating sign-in make sure your user is already login for not in previous session. you can check something like this.

    FirebaseAuth auth = FirebaseAuth.getInstance();
    if (auth.getCurrentUser() != null) {
      // already signed in
    } else {
      // not signed in 
    }

Create and launch sign-in intent

If the user is not signed-in then by the initiated sign-in process by creating auth intent. This you can specify service URL and include the link inside, or customized theme as well. You need to create and launch sign-in intent just like this.

    // Choose authentication providers
    List<AuthUI.IdpConfig> providers = Arrays.asList(
        new AuthUI.IdpConfig.EmailBuilder().build());

    // Create and launch sign-in intent
    startActivityForResult(
        AuthUI.getInstance()
            .createSignInIntentBuilder()
            .setAvailableProviders(providers)
            .build(),
        RC_SIGN_IN);

Check Response code on Activity Result

  @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // RC_SIGN_IN is the request code you passed into
    if (requestCode == 1234) {

      // Successfully signed in
      if (resultCode == RESULT_OK) {
        // Successfully signed in
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        Toast.makeText(getApplicationContext(), "Successfully signed in", Toast.LENGTH_SHORT)
            .show();
        launchMainActivity(user);
      }
    } else {
      // Sign in failed. If response is null the user canceled the sign-in flow using the back button. Otherwise check
      // response.getError().getErrorCode() and handle the error.
      Toast.makeText(getApplicationContext(), "Unable to Sign in", Toast.LENGTH_SHORT).show();
    }
  }
Finally, the login activity source code look like this.
package com.firebaseauthenticationuiexample;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.Arrays;
import java.util.List;

public class LoginActivity extends AppCompatActivity {
  private static final int RC_SIGN_IN = 1234;

  public static void startActivity(Context context) {
    Intent intent = new Intent(context, LoginActivity.class);
    context.startActivity(intent);
  }

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

    // find view
    Button buttonSignIn = findViewById(R.id.buttonSignIn);
    // Set onclick listener
    buttonSignIn.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        FirebaseAuth auth = FirebaseAuth.getInstance();
        if (auth.getCurrentUser() != null) {
          Toast.makeText(getApplicationContext(), "User already signed in, must sign out first",
              Toast.LENGTH_SHORT).show();
          // already signed in
        } else {
          // Choose authentication providers
          List<AuthUI.IdpConfig> providers = Arrays.asList(
              new AuthUI.IdpConfig.EmailBuilder().build());

          // Create and launch sign-in intent
          startActivityForResult(
              AuthUI.getInstance()
                  .createSignInIntentBuilder()
                  .setAvailableProviders(providers)
                  .build(),
              RC_SIGN_IN);
        }
      }
    });
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // RC_SIGN_IN is the request code you passed into
    if (requestCode == 1234) {

      // Successfully signed in
      if (resultCode == RESULT_OK) {
        // Successfully signed in
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        Toast.makeText(getApplicationContext(), "Successfully signed in", Toast.LENGTH_SHORT)
            .show();
        launchMainActivity(user);
      }
    } else {
      // Sign in failed. If response is null the user canceled the sign-in flow using the back button. Otherwise check
      // response.getError().getErrorCode() and handle the error.
      Toast.makeText(getApplicationContext(), "Unable to Sign in", Toast.LENGTH_SHORT).show();
    }
  }

  private void launchMainActivity(FirebaseUser user) {
    if (user != null) {
      MainActivity.startActivity(this, user.getDisplayName());
      finish();
    }
  }
}
Implement logout in MainActivity

Your login stuff is done. Now I’m going to explain the logout part. open the main activity layout file add one button for perform logout.

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

  <Button
      android:id="@+id/buttonLogout"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Logout"
      android:textAllCaps="false"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"

      />
  <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginBottom="16dp"
      android:text="Welcome"
      android:textColor="@color/colorAccent"
      android:textSize="20sp"
      app:layout_constraintBottom_toTopOf="@+id/buttonLogout"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      />
</androidx.constraintlayout.widget.ConstraintLayout>
Let’s open the main activity source file

Doing signout firebase auth provider gives callback onComplete methods. just like below.

package com.firebaseauthenticationuiexample;

import android.content.Context;
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.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

public class MainActivity extends AppCompatActivity {
  private static final String ARG_NAME = "username";

  public static void startActivity(Context context, String username) {
    Intent intent = new Intent(context, MainActivity.class);
    intent.putExtra(ARG_NAME, username);
    context.startActivity(intent);
  }

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

    TextView textView = findViewById(R.id.textView);
    if (getIntent().hasExtra(ARG_NAME)) {
      textView.setText(String.format("Welcome - %s", getIntent().getStringExtra(ARG_NAME)));
    }

    Button logout = findViewById(R.id.buttonLogout);
    logout.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        AuthUI.getInstance()
            .signOut(MainActivity.this)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
              public void onComplete(@NonNull Task<Void> task) {
                // user is now signed out
                Toast.makeText(getApplicationContext(), "User has signed out!", Toast.LENGTH_SHORT)
                    .show();
                launchLoginActivity();
              }
            });
      }
    });
  }

  private void launchLoginActivity() {
    LoginActivity.startActivity(MainActivity.this);
    finish();
  }
}

With the help of this android app tutorial, We have learned firebaseui for authentication with email I hope it’s helpful for you, Help me by sharing this post with all your friends who learning android app development.

Keep in touch

If you want to keep in touch and get an email when I write new blog posts, follow me on facebook or subscribe usIt only takes about 10 seconds to register. 

Still, if you have any queries please put your comment below.

Write A Comment