Skip to content
Related Articles

Related Articles

Google Signing using Firebase Authentication in Android using Java

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 12 May, 2022

Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides email and password authentication without any overhead of building the backend for user authentication. Google Sign-In is a secure way to authenticate users in your apps. It reduces the hassle of dealing with and handling those extra passwords by the user to get authenticated to the app. Firebase offers a great number of options to implement Login in your app like Email, Phone number, Google, Facebook, etc.

What we are going to build in this article?

Here is a sample video of what we are going to build in this article. Note that we will be using Java language to make this application.

Step by Step Implementation

Step 1. Create a New Project

  • Open a new project.
  • We will be working on Empty Activity with language as Java. Leave all other options unchanged.
  • Name the application at your convenience.
  • There will be two default files named activity_main.xml and MainActivity.java.

If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?

Step 2. Connecting Firebase with our application

Name your project and click on continue and Connect your firebase to your google account.

After completion of the project, the following interface will appear-

Now enter the package name and the name of your application. To enter SHA-1 value follow the steps- Go to Gradle > Task > android >  signing report

After opening the signing report you will get the value of SHA-1 as shown below. Copy it and use it in firebase.

After completing the above step download the google-services.json config file provided there and paste it in android studio. Navigate to project  > app > src and paste it.

Go to authentication.

Go to Sign-in-method and enable google sign-in.

Step 3. Adding required dependencies and plugins

Navigate to Gradle Scripts > build.gradle(project) and add the following dependency in it-

classpath 'com.google.gms:google-services:4.3.10'

Navigate to Gradle Scripts > build.gradle(module) and add the following plugin in it-

apply plugin: 'com.google.gms.google-services'

Navigate to Gradle Scripts > build.gradle(module) and add the following dependencies in it-

implementation 'com.google.firebase:firebase-auth:19.4.0'
implementation 'com.google.android.gms:play-services-auth:18.1.0'
implementation 'com.github.bumptech.glide:glide:4.11.0'

Step 4. Adding Internet permission

Go to the AndroidManifest.xml file and add the following piece of code to it-

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

Step 5. Working with XML files

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <com.google.android.gms.common.SignInButton
        android:id="@+id/bt_sign_in"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="16dp" />
 
</RelativeLayout>

Navigate to app > right-click > new > activity > empty activity and name it as ProfileActivity. Use the following code in activity_profile.xml file-

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="16dp"
    tools:context=".ProfileActivity">
 
    <ImageView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:id="@+id/iv_image"/>
   
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_name"
        android:textSize="24sp"
        android:textStyle="bold"
        android:textColor="@color/design_default_color_primary"/>
   
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt_logout"
        android:text="Logout"
        android:layout_marginTop="32dp"/>
 
</LinearLayout>

Step 6. Working with Java files

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




package com.example.googlesigninfirebase;
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
 
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
 
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
 
public class MainActivity extends AppCompatActivity {
 
    // Initialize variables
    SignInButton btSignIn;
    GoogleSignInClient googleSignInClient;
    FirebaseAuth firebaseAuth;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Assign variable
        btSignIn=findViewById(R.id.bt_sign_in);
 
        // Initialize sign in options
          // the client-id is copied form
          // google-services.json file
        GoogleSignInOptions googleSignInOptions=new GoogleSignInOptions.Builder(
                GoogleSignInOptions.DEFAULT_SIGN_IN
        ).requestIdToken("438431947620-ecpi41uk3dhhf4mv8g8q993k3vs49ltm.apps.googleusercontent.com")
                .requestEmail()
                .build();
 
        // Initialize sign in client
        googleSignInClient= GoogleSignIn.getClient(MainActivity.this
        ,googleSignInOptions);
 
        btSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Initialize sign in intent
                Intent intent=googleSignInClient.getSignInIntent();
                // Start activity for result
                startActivityForResult(intent,100);
            }
        });
 
        // Initialize firebase auth
        firebaseAuth=FirebaseAuth.getInstance();
        // Initialize firebase user
        FirebaseUser firebaseUser=firebaseAuth.getCurrentUser();
        // Check condition
        if(firebaseUser!=null)
        {
            // When user already sign in
            // redirect to profile activity
            startActivity(new Intent(MainActivity.this,ProfileActivity.class)
            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        }
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Check condition
        if(requestCode==100)
        {
            // When request code is equal to 100
            // Initialize task
            Task<GoogleSignInAccount> signInAccountTask=GoogleSignIn
                    .getSignedInAccountFromIntent(data);
 
            // check condition
            if(signInAccountTask.isSuccessful())
            {
                // When google sign in successful
                // Initialize string
                String s="Google sign in successful";
                // Display Toast
                displayToast(s);
                // Initialize sign in account
                try {
                    // Initialize sign in account
                    GoogleSignInAccount googleSignInAccount=signInAccountTask
                            .getResult(ApiException.class);
                    // Check condition
                    if(googleSignInAccount!=null)
                    {
                        // When sign in account is not equal to null
                        // Initialize auth credential
                        AuthCredential authCredential= GoogleAuthProvider
                                .getCredential(googleSignInAccount.getIdToken()
                                ,null);
                        // Check credential
                        firebaseAuth.signInWithCredential(authCredential)
                                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                                    @Override
                                    public void onComplete(@NonNull Task<AuthResult> task) {
                                        // Check condition
                                        if(task.isSuccessful())
                                        {
                                            // When task is successful
                                            // Redirect to profile activity
                                            startActivity(new Intent(MainActivity.this
                                            ,ProfileActivity.class)
                                            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                                            // Display Toast
                                            displayToast("Firebase authentication successful");
                                        }
                                        else
                                        {
                                            // When task is unsuccessful
                                            // Display Toast
                                            displayToast("Authentication Failed :"+task.getException()
                                            .getMessage());
                                        }
                                    }
                                });
 
                    }
                }
                catch (ApiException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
 
    private void displayToast(String s) {
        Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
    }
}

Go to the ProfileActivity.java file and use the following code in it-

Java




package com.example.googlesigninfirebase;
 
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
 
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 com.bumptech.glide.Glide;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
 
public class ProfileActivity extends AppCompatActivity {
 
    // Initialize variable
    ImageView ivImage;
    TextView tvName;
    Button btLogout;
    FirebaseAuth firebaseAuth;
    GoogleSignInClient googleSignInClient;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
 
        // Assign variable
        ivImage=findViewById(R.id.iv_image);
        tvName=findViewById(R.id.tv_name);
        btLogout=findViewById(R.id.bt_logout);
 
        // Initialize firebase auth
        firebaseAuth=FirebaseAuth.getInstance();
         
          // Initialize firebase user
        FirebaseUser firebaseUser=firebaseAuth.getCurrentUser();
         
          // Check condition
        if(firebaseUser!=null)
        {
            // When firebase user is not equal to null
            // Set image on image view
            Glide.with(ProfileActivity.this)
                    .load(firebaseUser.getPhotoUrl())
                    .into(ivImage);
            // set name on text view
            tvName.setText(firebaseUser.getDisplayName());
        }
 
        // Initialize sign in client
        googleSignInClient= GoogleSignIn.getClient(ProfileActivity.this
        , GoogleSignInOptions.DEFAULT_SIGN_IN);
 
        btLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Sign out from google
                googleSignInClient.signOut().addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        // Check condition
                        if(task.isSuccessful())
                        {
                            // When task is successful
                            // Sign out from firebase
                            firebaseAuth.signOut();
                             
                              // Display Toast
                            Toast.makeText(getApplicationContext(), "Logout successful", Toast.LENGTH_SHORT).show();
 
                            // Finish activity
                            finish();
                        }
                    }
                });
            }
        });
    }
}

Here is the final output of our application.

Output:

Also, you can see that inside Firebase data of users is being stored-


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!