Register authenticated users with Facebook in Firebase Database

Asked

Viewed 53 times

1

Good night! Guys, I’m using Facebook login in my app and would like to register the user information in the database or firestore Realtime, as the name and email for example, I’ve recovered the logged in user information, I’ve already done the authentication, but I don’t know how to save this data, I can easily save when I use the email and password method, but with facebook the login method is different. What is the best way for me to save this data ?

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    callbackManager.onActivityResult(requestCode, resultCode, data);
    super.onActivityResult(requestCode, resultCode, data);

}

private void firebaseAutenticacaoFacebook(AccessToken accessToken) {

    AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
    mAuth.signInWithCredential( credential )
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {

                        FirebaseUser user = mAuth.getCurrentUser();
                        
                        Usuario usuario = new Usuario();
                        
                        usuario.setEmail( user.getEmail() );
                        usuario.setNome ( user.getDisplayName());
                        usuario.setFoto ( user.getPhotoUrl().toString());


                        MainScreen();

                    } else {

                        String excecao = "";

                        try
                        {
                            throw task.getException();

                        }catch (FirebaseAuthUserCollisionException e)
                        {
                            excecao = "Este email ja foi cadastrado!";

                        }catch (Exception e)
                        {
                            excecao = "Erro ao logar usuário!" + e.getMessage();
                        }

                        Toast.makeText(getApplicationContext(), excecao , Toast.LENGTH_SHORT).show();

                    }
                }
            });
}

 public void MainScreen(){

    Intent i = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(i);
    finish();
}

1 answer

1


as the documentation in Read and write data on android

Have the instance:

private DatabaseReference mDatabase;
// ...
mDatabase = FirebaseDatabase.getInstance().getReference();

the User class

@IgnoreExtraProperties
public class User {

    public String username;
    public String email;

    public User() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    }

    public User(String username, String email) {
        this.username = username;
        this.email = email;
    }

}

and the function that will save to firebase:

private void writeNewUser(String userId, String name, String email) {
    User user = new User(name, email);

    mDatabase.child("users").child(userId).setValue(user);
}

by sample of your code, you can do:

//...
FirebaseUser user = mAuth.getCurrentUser();

writeNewUser(user.getUid(), user.getDisplayName(), user.getEmail());
//...
  • Thank you, it worked perfectly, only curiosity is that this credential process will always be called when making a login request with Facebook, if I come to save for example the age of the user next to the name and already saved Email and then log back in with the same account, this function to save in Firebase is called again and will overwrite the current user, that is, any future change within a user will be lost if the user logs in again, leaving only the initial information, Name and Email.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.