Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android Firebase getDisplayName()返回空值_Android_Firebase_Firebase Realtime Database_Firebase Authentication - Fatal编程技术网

Android Firebase getDisplayName()返回空值

Android Firebase getDisplayName()返回空值,android,firebase,firebase-realtime-database,firebase-authentication,Android,Firebase,Firebase Realtime Database,Firebase Authentication,我有以下代码,应该返回Firebase登录的用户数据,它返回没有问题的用户ID和电子邮件,但是名称的值返回空或null。就好像用户注册时没有名字一样,但在注册中出现了用户的名字。有人知道为什么吗?我已经搜索过了,它看起来有一些Firebase getDisplayName的bug。有人有解决办法吗 public static FirebaseUser getUsuarioAtual() { FirebaseAuth usuario = ConfiguracaoFirebase.g

我有以下代码,应该返回Firebase登录的用户数据,它返回没有问题的用户ID和电子邮件,但是名称的值返回空或null。就好像用户注册时没有名字一样,但在注册中出现了用户的名字。有人知道为什么吗?我已经搜索过了,它看起来有一些Firebase getDisplayName的bug。有人有解决办法吗

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;
    }
返回FirebaseAuth的实例:

public static FirebaseAuth getFirebaseAutenticacao(){

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

        return auth;

    }
创建帐户的代码:

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();

                }

            }
        });

    }
更新用户名:

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

    }

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

比如说

    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(); 
...
检查UserProfileChangeRequest

重要的

如果您使用Google登录之类的提供商登录,它将自动处理您的显示名称和个人资料照片,只需调用user.getDisplayName而不进行设置,即可正确完成任务

请记住,当您使用emailAndPassword创建新帐户时,帐户ID和电子邮件会自动存储在Firebase中,这就是为什么您可以访问这些数据而无需设置它们的原因。这是随用户一起创建的元数据示例。在这种情况下,定义用户的元数据仅为UserID和电子邮件

但是从来没有为该帐户设置displayName或photoUri,这就是为什么在创建新帐户时需要设置它们的原因,正如我前面提到的

小费

避免这样做,当应用程序扩展时,你会感到困惑

public static FirebaseAuth getFirebaseAutenticacao(){

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

        return auth;

    }
取而代之的是,用这个

FirebaseAuth usuario = FirebaseAuth.getInstance();
然后用你的Usario来得到你需要的东西

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

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

比如说

    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(); 
...
检查UserProfileChangeRequest

重要的

如果您使用Google登录之类的提供商登录,它将自动处理您的显示名称和个人资料照片,只需调用user.getDisplayName而不进行设置,即可正确完成任务

请记住,当您使用emailAndPassword创建新帐户时,帐户ID和电子邮件会自动存储在Firebase中,这就是为什么您可以访问这些数据而无需设置它们的原因。这是随用户一起创建的元数据示例。在这种情况下,定义用户的元数据仅为UserID和电子邮件

但是从来没有为该帐户设置displayName或photoUri,这就是为什么在创建新帐户时需要设置它们的原因,正如我前面提到的

小费

避免这样做,当应用程序扩展时,你会感到困惑

public static FirebaseAuth getFirebaseAutenticacao(){

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

        return auth;

    }
取而代之的是,用这个

FirebaseAuth usuario = FirebaseAuth.getInstance();
然后用你的Usario来得到你需要的东西

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

您好,您可以在我编辑的代码中看到,我在创建新帐户时设置了名称。我真的不确定在我的情况下什么时候使用这个AuthStateListener,因为我对Firebase方法知之甚少,你能告诉我吗?搜索Firebase AuthListener来设置一个监听器,该监听器将知道当前用户何时登录或未登录、何时注销等等。我遇到了同样的问题,但使用Google帐户登录。UserProfileChangeRequest使我能够解决它。谢谢你,加斯顿!您好,您可以在我编辑的代码中看到,我在创建新帐户时设置了名称。我真的不确定在我的情况下什么时候使用这个AuthStateListener,因为我对Firebase方法知之甚少,你能告诉我吗?搜索Firebase AuthListener来设置一个监听器,该监听器将知道当前用户何时登录或未登录、何时注销等等。我遇到了同样的问题,但使用Google帐户登录。UserProfileChangeRequest使我能够解决它。谢谢你,加斯顿!