1

I have a problem in Google sign in, whenever I sign in with Google, I set the credentials to be added to the database also ( like: name & email ), but the problem that all is working except, that now each time I sign in with same google account, it gets added again in the database ( same credentials over and over), so I want to check if the Google sign-in credentials already exist in the database, no need to add the credential all over.

Here the Google signin code in onCreate :

private FirebaseAuth firebaseAuth;
private FirebaseFirestore firebaseFirestore;
private GoogleSignInClient mGoogleSignInClient;
private static final int RC_SIGN_IN = 100;


googleImageBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            progresBarDim.setVisibility(View.VISIBLE);
            signIn();
        }
    });

// TODO : Firebase Authentication
    firebaseAuth = FirebaseAuth.getInstance();
    firebaseFirestore = FirebaseFirestore.getInstance();
    googleRequest();

and here's the methods for google signIn :

private void googleRequest(){
    // 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) {
            progresBarDim.setVisibility(View.GONE);
            // 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);
    firebaseAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(LoginActivity.this);
                        final String name = signInAccount.getDisplayName().trim();
                        final String email =signInAccount.getEmail().trim();

                        Map<Object, String> userdata = new HashMap<>();
                        userdata.put("Nom et prénom", name);
                        userdata.put("Address émail", email);

                        firebaseFirestore.collection("USERS")
                                .add(userdata);

                        // Sign in success, update UI with the signed-in user's information
                        FirebaseUser user = firebaseAuth.getCurrentUser();
                        Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
                        startActivity(intent);

                    } else {
                        progresBarDim.setVisibility(View.GONE);
                        // If sign in fails, display a message to the user.
                        Toast.makeText(LoginActivity.this, "sorry auth failed!", Toast.LENGTH_SHORT).show();
                    }
                    progresBarDim.setVisibility(View.GONE);

                    // ...
                }
            });
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Lamine
  • 25
  • 5

1 Answers1

1

it gets added again in Realtime database( same credentials over and over)

This is happening because you are adding the data over and over again. Responsible for this behavior is the following line of code:

firebaseFirestore.collection("USERS")
                            .add(userdata);

When you are using add(Object data):

Adds a new document to this collection with the specified data, assigning it a document ID automatically.

So each time you are calling the above line of code, a new document is created. To solve this, you should add the data to a specific location, for instance, at the following reference:

Firestore-root
  |
  --- users (collection)
       |
       --- uid  (document)
            |
            --- Nom et prénom: "User Name"
            |
            --- Address émail: "User Email"

You can get the uid from the FirebaseUser object, using the following line of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

Now, to write the data, use the following code:

firebaseFirestore.collection("USERS").document(uid)
                            .set(userdata);

But instead of using add(), I have used set() on DocumentReference object. In order to avoid writing the data every time a user signs in with Google, you need to check if the user already exists and this can be done using my answer from the following post:

But instead of checking the user name, you should check against the uid.

P.S. Your code says that you are using Cloud Firestore and not Firebase Realtime Database, as you set the tag.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • 1
    Thanks Alex for the solution and for the reminder on firestore instead of firebase , i didn't notice what i wrote, i added the(uid) document and (set) instead of (add) like you mentioned, and that just worked perfectly – Lamine Apr 17 '20 at 18:42