In today’s world almost, everyone wants to save their time from inputting their details over and over. So, instead of providing credentials from start people love to go with other options like using Google signIn, Facebook SignIn etc. That’s why today we are going to create Firebase login with google.
If you are new in firebase or tired finding relevant posts to learn google authentication with firebase. Then, your search is over.
Firebase is quite a powerful and easy way to perform authentications. We all know about the firebase as a database but it is not just a database. It provides Crashlytics, Cloud hosting, Storage, realtime database, authentication and much more.
Firebase authentication in android studio provides varies ways like
- Phone Authentication
- Facebook Authentication
- Email Authentication
- Password Authentication
- Github Authentication
- Twitter Authentication
- Play Games Authentication
- Microsoft Authentication
- Anonymous Authentication
Firebase login with google
In this tutorial, we will learn how to create a google authentication in android studio using firebase. Firebase Authentication functions are the same as in the phone Authentication in the android tutorial but have few google oriented methods.
So before getting started, let me tell you the overview of how we will achieve firebase login with google. We need 3 main functions in our activity to perform google authentication.
Firstly, we will create a request for google to show us the popup, which has email accounts. This function will be in onCreate activity and called when activity created.
Secondly, On the click of Sign In with Google button, the second function will be called. In that function, we will simply show that pop-up window using Intent to get mails from google.
Thirdly, when the user selects some mail then that intent will return some data so we will handle that data. If it is a success case then we will pass that data in firebase login using credentials function.
Ok so let’s get started with our coding.
Firebase login with google (Source Code)
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
android:orientation="vertical"><LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="100dp"
android:orientation="vertical"
android:paddingRight="20dp"
android:paddingLeft="20dp"><ImageView
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_gravity="center_horizontal"
android:src="@drawable/google_icon" /><TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/baloo"
android:includeFontPadding="false"
android:paddingTop="20sp"
android:shadowColor="#0E0E0E"
android:text="Sign In"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="45sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:includeFontPadding="false"
android:shadowColor="#0E0E0E"
android:text="Sign-In with Google using Firebase!"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="14sp" /><Space
android:layout_width="match_parent"
android:layout_height="100dp"/><Button
android:id="@+id/google_signIn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/round_btn"
android:drawableLeft="@drawable/google"
android:elevation="8dp"
android:text="Sign In with Google"
android:textColor="#fff" /><LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="100dp"
android:paddingRight="100dp"
android:layout_marginTop="160dp"><ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:src="@drawable/facebook"
android:layout_weight="1"/><ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:src="@drawable/google_plus"
android:layout_weight="1"/><ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:src="@drawable/twitter"
android:layout_weight="1"/></LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="bottom"
android:includeFontPadding="false"
android:shadowColor="#0E0E0E"
android:text="Taimoor Sikander - Coding with T"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="14sp" /></LinearLayout>
</ScrollView>
package com.taimoorsikander.googleauthtutorial;import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
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.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 {
private GoogleSignInClient mGoogleSignInClient;
private final static int RC_SIGN_IN = 123;
private FirebaseAuth mAuth;@Override
protected void onStart() {
super.onStart();FirebaseUser user = mAuth.getCurrentUser();
if(user!=null){
Intent intent = new Intent(getApplicationContext(),Profile.class);
startActivity(intent);
}}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);mAuth = FirebaseAuth.getInstance();
createRequest();
findViewById(R.id.google_signIn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signIn();
}
});}
private void createRequest() {
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
// ...
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = mAuth.getCurrentUser();
Intent intent = new Intent(getApplicationContext(),Profile.class);
startActivity(intent);} else {
Toast.makeText(MainActivity.this, "Sorry auth failed.", Toast.LENGTH_SHORT).show();}
// ...
}
});
}}
<?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=".Profile"><Button
android:id="@+id/logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Logout"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" /><TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="63dp"
android:layout_marginTop="97dp"
android:text="TextView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" /><TextView
android:id="@+id/mail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="28dp"
android:text="TextView"
app:layout_constraintStart_toStartOf="@+id/name"
app:layout_constraintTop_toBottomOf="@+id/name" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.taimoorsikander.googleauthtutorial;import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.firebase.auth.FirebaseAuth;public class Profile extends AppCompatActivity {
TextView name, mail;
Button logout;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);logout = findViewById(R.id.logout);
name = findViewById(R.id.name);
mail = findViewById(R.id.mail);GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if(signInAccount != null){
name.setText(signInAccount.getDisplayName());
mail.setText(signInAccount.getEmail());
}logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
});}
}
Get Complete Source code for Bull’s Rent App
To learn in detail just follow our Youtube tutorial..
Android Related Videos
- Design a Modern Dashboard
- Material Design Login Screen with Shared Animations
- Create a Navigation Drawer Material Design in 2020
- Design Responsive Android App to fit all screen sizes
Related Articles that you might want to check out.
- Create a new project in android studio for beginners?
- How to create an Account on Fiverr and start earning?
- Create a Gig on Fiverr and start selling specific services.
- How To Start Blogging and Make Money?
Our Projects Make Us Proud