Search code examples
javaandroidfirebasegoogle-signin

How do i implement a login with google firebase in my java application


I've looked at countless youtube videos but nothing try works and I don't know why I've also read through the documentation but with no luck... I'm using android studio and coding in java its a simple problem but I cant seem to figure it out, here is the code I have for the button I've kind of left out the old code that I had in the "//google sign in request" as it does not work and makes no sense. I've also successfully connected my firebase to the project and added the SHA-1 fingerprint.

package com.example.firebasegoogleauth4;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.auth.api.identity.BeginSignInRequest;
import com.google.android.gms.auth.api.identity.SignInClient;

public class MainActivity extends AppCompatActivity {

    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        btn = findViewById(R.id.button1);
        
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //google sign in request 
            }
        });
    }
}

Solution

  • it seems like you're trying to implement a Google Sign-In functionality using Firebase Authentication in an Android Studio project.

    To implement Google Sign-In with Firebase, you'll need to perform the following steps:

    1. Add the necessary dependencies: In your project's build.gradle file, make sure you have the necessary dependencies for Google Sign-In and Firebase Authentication. For example:
    dependencies {
        // Other dependencies...
        implementation 'com.google.android.gms:play-services-auth:19.2.0'
        implementation 'com.google.firebase:firebase-auth:21.0.1'
    }
    
    1. Configure Google Sign-In in the Firebase console: Make sure you have enabled the Google Sign-In provider in the Firebase console and added the appropriate SHA-1 fingerprint for your Android app.

    2. Set up the Google Sign-In request:

    import com.google.android.gms.auth.api.signin.GoogleSignIn;
    import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
    import com.google.android.gms.auth.api.signin.GoogleSignInClient;
    
    // ...
    
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // 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
            GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(MainActivity.this, gso);
    
            // Start the sign-in intent
            Intent signInIntent = googleSignInClient.getSignInIntent();
            startActivityForResult(signInIntent, RC_SIGN_IN);
        }
    });
    

    Make sure to replace R.string.default_web_client_id with your own web client ID from the Firebase console.

    1. Handle the sign-in result:
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                // Google sign-in was successful
                GoogleSignInAccount account = task.getResult(ApiException.class);
                
                // Get the user's ID token and authenticate with Firebase
                String idToken = account.getIdToken();
                AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
                FirebaseAuth.getInstance().signInWithCredential(credential)
                        .addOnCompleteListener(MainActivity.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 = FirebaseAuth.getInstance().getCurrentUser();
                                    String displayName = user.getDisplayName();
                                    Toast.makeText(MainActivity.this, "Welcome " + displayName, Toast.LENGTH_SHORT).show();
                                } else {
                                    // Sign-in failed, display a message to the user
                                    Toast.makeText(MainActivity.this, "Sign-in failed", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
            } catch (ApiException e) {
                // Google sign-in failed
                Toast.makeText(MainActivity.this, "Google Sign-in Failed", Toast.LENGTH_SHORT).show();
            }
        }
    }
    

    Be sure to define a constant RC_SIGN_IN for the request code.

    Remember to also set up Firebase Authentication in your project and configure it in the Firebase console.

    Make sure you