Firebase getDisplayName() returns empty

≯℡__Kan透↙ 提交于 2020-12-13 11:38:06

问题


I have the following code that should return the user data logged in by Firebase, it returns the user with no problem, ID and Email, but the value of the name returns empty or null. As if the user had been registered without a name, but in the register the name of the user appears. Does anyone know why? I already searched it and it looks like it has some bug with the Firebase getDisplayName. Does anyone have a solution?

public static FirebaseUser getUsuarioAtual() {
        FirebaseAuth usuario = ConfiguracaoFirebase.getFirebaseAutenticacao();
        return usuario.getCurrentUser();
    }

    public static Usuario getDadosUsuarioLogado() {
        FirebaseUser firebaseUser = getUsuarioAtual();

        Usuario usuario = new Usuario();
        usuario.setId(firebaseUser.getUid());
        usuario.setEmail(firebaseUser.getEmail());
        usuario.setNome(firebaseUser.getDisplayName());

        return usuario;
    }

Returns the instance of FirebaseAuth:

public static FirebaseAuth getFirebaseAutenticacao(){

        if (auth == null) {
            auth = FirebaseAuth.getInstance();
        }

        return auth;

    }

Code that creates an account:

public void cadastrarUsuario(final Usuario usuario){

        autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();
        autenticacao.createUserWithEmailAndPassword(
          usuario.getEmail(),
          usuario.getSenha()
        ).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if (task.isSuccessful()){

                    try {
                        String idUsuario = task.getResult().getUser().getUid();
                        usuario.setId( idUsuario );
                        usuario.salvar();

                        UsuarioFirebase.atualizarNomeUsuario(usuario.getNome());

                        //Redireciona o usuário com base no seu tipo
                        if ( verificaTipoUsuario() == "P" ) {

                            startActivity(new Intent(CadastroActivity.this, PassageiroActivity.class));
                            finish();

                            Toast.makeText(CadastroActivity.this, "Cadastro realizado com sucesso!", Toast.LENGTH_SHORT).show();

                        } else {

                            startActivity(new Intent(CadastroActivity.this, RequisicoesActivity.class));
                            finish();

                            Toast.makeText(CadastroActivity.this, "Parabéns! Você agora é nosso parceiro!", Toast.LENGTH_SHORT).show();

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                } else {

                    String excecao = "";
                    try {
                        throw task.getException();
                    } catch ( FirebaseAuthWeakPasswordException e ) {
                        excecao = "Digite uma senha mais forte!";
                    } catch ( FirebaseAuthInvalidCredentialsException e ) {
                        excecao = "Por favor, digite um e-mail válido";
                    } catch ( FirebaseAuthUserCollisionException e ) {
                        excecao = "Já existe uma conta com esse e-mail";
                    } catch ( Exception e ) {
                        excecao = "Erro ao cadastrar usuário: " + e.getMessage();
                        e.printStackTrace();
                    }

                    Toast.makeText(CadastroActivity.this, excecao, Toast.LENGTH_SHORT).show();

                }

            }
        });

    }

Update User Name:

public static boolean atualizarNomeUsuario (String nome) {

        try {

            FirebaseUser user = getUsuarioAtual();
            UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder()
                    .setDisplayName( nome )
                    .build();
            user.updateProfile(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {

                    if (!task.isSuccessful()){
                        Log.d("Perfil", "Erro ao atualizar nome de perfil.");
                    }

                }
            });

            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

回答1:


In order to get your display name , you will need to set it up when you create the new account with email and password

For example

    mAuth.createUserWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if(task.isSuccessful()){
                    saveUser(email,pass,name);
                    FirebaseUser user = mAuth.getCurrentUser();
                    UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder().setDisplayName(name).build();
                    user.updateProfile(profileUpdates);
                    finish(); 
...

Now, you will need an AuthStateListener, and then when it's complete (you successful logged in or created the account), you can get the name. Since firebase manages this Asynchronous

mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
             usuario.setNome(firebaseUser.getDisplayName());
            } else {
                finish();
...

Check UserProfileChangeRequest Here

Important

If you log in with a provider like Google sign-in, it will handle automatically your display name (as well as the profile photo), and just calling user.getDisplayName() without setting it will do the job correctly

Remember that when you create a new account with emailAndPassword, the ID of the account and the email are automatically stored at Firebase, that's why you can access those data without setting them. This is an example of the metadata that is created along with the user. In this case, the metadata defining your user is only the UserID and the Email.

But there is never set a displayName or a photoUri for that account, that's why you need to also set them up when you create a new account as I mentioned above.

Tip

Avoid doing your owns methods like this, you will be confused when the app scales.

public static FirebaseAuth getFirebaseAutenticacao(){

        if (auth == null) {
            auth = FirebaseAuth.getInstance();
        }

        return auth;

    }

instead, just use this

FirebaseAuth usuario = FirebaseAuth.getInstance();

And then use your usuario to get what you need

usuario.getCurrentUser().getUid(); //for example, getting the uid of the user logged in


来源:https://stackoverflow.com/questions/53395256/firebase-getdisplayname-returns-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!