Firebase getDisplayName()返回空 [英] Firebase getDisplayName() returns empty

查看:49
本文介绍了Firebase getDisplayName()返回空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码应该返回Firebase登录的用户数据,它返回的用户没有问题,ID和Email,但名称的值返回空或null.好像用户已经注册时没有名字,但是在用户名中出现了用户名.有人知道为什么吗?我已经搜索了它,它似乎在Firebase getDisplayName中存在一些错误.有人有解决方案吗?

 公共静态FirebaseUser getUsuarioAtual(){FirebaseAuth usuario = ConfiguracaoFirebase.getFirebaseAutenticacao();返回usuario.getCurrentUser();}公共静态Usuario getDadosUsuarioLogado(){FirebaseUser firebaseUser = getUsuarioAtual();Usuario usuario =新的Usuario();usuario.setId(firebaseUser.getUid());usuario.setEmail(firebaseUser.getEmail());usuario.setNome(firebaseUser.getDisplayName());退货} 

返回FirebaseAuth的实例:

 公共静态FirebaseAuth getFirebaseAutenticacao(){如果(auth == null){auth = FirebaseAuth.getInstance();}返回认证;} 

创建帐户的代码:

  public void cadastrarUsuario(final Usuario usuario){autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();autenticacao.createUserWithEmailAndPassword(usuario.getEmail(),usuario.getSenha()).addOnCompleteListener(this,new OnCompleteListener< AuthResult>(){@Overridepublic void onComplete(@NonNull Task< AuthResult>任务){如果(task.isSuccessful()){尝试 {字符串idUsuario = task.getResult().getUser().getUid();usuario.setId(idUsuario);usuario.salvar();UsuarioFirebase.atualizarNomeUsuario(usuario.getNome());//Redireciona ousuáriocom base no seu tipo如果(verificaTipoUsuario()=="P"){startActivity(new Intent(CadastroActivity.this,PassageiroActivity.class));结束();Toast.makeText(CadastroActivity.this,"Cadastro realizado com sucesso!",Toast.LENGTH_SHORT).show();} 别的 {startActivity(new Intent(CadastroActivity.this,RequisicoesActivity.class));结束();Toast.makeText(CadastroActivity.this,Parabéns!Vocêagoraénosso parceiro!",Toast.LENGTH_SHORT).show();}} catch(Exception e){e.printStackTrace();}} 别的 {字符串excecao =";尝试 {抛出task.getException();} catch(FirebaseAuthWeakPasswordException e){excecao ="Digite uma senha mais forte!";} catch(FirebaseAuthInvalidCredentialsException e){excecao =拜托,请发送电子邮件给我]} catch(FirebaseAuthUserCollisionException e){excecao =已存在uma conta com esse电子邮件";} catch(Exception e){excecao =使用错误的地籍:" + e.getMessage();e.printStackTrace();}Toast.makeText(CadastroActivity.this,excecao,Toast.LENGTH_SHORT).show();}}});} 

更新用户名:

 公共静态布尔值atualizarNomeUsuario(字符串名称){尝试 {FirebaseUser用户= getUsuarioAtual();UserProfileChangeRequest配置文件=新的UserProfileChangeRequest.Builder().setDisplayName(nome).建造();user.updateProfile(profile).addOnCompleteListener(new OnCompleteListener< Void>(){@Overridepublic void onComplete(@NonNull Task< Void>任务){如果(!task.isSuccessful()){Log.d("Perfil","Erro aoualualarar nome de perfil.");}}});返回true;} catch(Exception e){e.printStackTrace();返回false;}} 

解决方案

要获取显示名称,您需要在使用电子邮件和密码创建新帐户时进行设置

例如

  mAuth.createUserWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener< AuthResult>(){@Overridepublic void onComplete(@NonNull Task< AuthResult>任务){if(task.isSuccessful()){saveUser(email,pass,name);FirebaseUser用户= mAuth.getCurrentUser();UserProfileChangeRequest profileUpdates =新的UserProfileChangeRequest.Builder().setDisplayName(name).build();user.updateProfile(profileUpdates);结束();... 

现在,您将需要一个 AuthStateListener ,然后完成该操作(成功登录或创建帐户)后,即可获得名称.由于Firebase会管理此异步

  mAuthListener = new FirebaseAuth.AuthStateListener(){@Override公共无效onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth){FirebaseUser用户= firebaseAuth.getCurrentUser();如果(用户!= null){usuario.setNome(firebaseUser.getDisplayName());} 别的 {结束();... 

检查UserProfileChangeRequest

但是从来没有为该帐户设置displayName或photoUri,这就是为什么如上所述创建新帐户时也需要设置它们的原因.

提示

避免使用自己的方法,当应用扩展时,您会感到困惑.

 公共静态FirebaseAuth getFirebaseAutenticacao(){如果(auth == null){auth = FirebaseAuth.getInstance();}返回认证;} 

相反,只需使用此

  FirebaseAuth使用情况= FirebaseAuth.getInstance(); 

然后使用您的用法来获得所需的内容

  usuario.getCurrentUser().getUid();//例如,获取用户的uid登录 

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;
        }

    }

解决方案

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

这篇关于Firebase getDisplayName()返回空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆