Firebase getDisplayName() returns empty












0















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

}









share|improve this question





























    0















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

    }









    share|improve this question



























      0












      0








      0








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

      }









      share|improve this question
















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

      }






      firebase android-studio firebase-realtime-database firebase-authentication






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 '18 at 15:20







      C.Oli

















      asked Nov 20 '18 at 14:31









      C.OliC.Oli

      87




      87
























          1 Answer
          1






          active

          oldest

          votes


















          0














          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.



          enter image description here



          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





          share|improve this answer


























          • Hi, as you can see in the codes I edited, I set the name when I create a new account. I'm not really sure when to use this AuthStateListener in my situation, as I know little about Firebase methods, could you show me?

            – C.Oli
            Nov 20 '18 at 15:33











          • search for Firebase AuthListener to setup a listener that will know when the current user is logged in or not, when it has signed out and more

            – Gastón Saillén
            Nov 20 '18 at 17:22











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53395256%2ffirebase-getdisplayname-returns-empty%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          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.



          enter image description here



          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





          share|improve this answer


























          • Hi, as you can see in the codes I edited, I set the name when I create a new account. I'm not really sure when to use this AuthStateListener in my situation, as I know little about Firebase methods, could you show me?

            – C.Oli
            Nov 20 '18 at 15:33











          • search for Firebase AuthListener to setup a listener that will know when the current user is logged in or not, when it has signed out and more

            – Gastón Saillén
            Nov 20 '18 at 17:22
















          0














          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.



          enter image description here



          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





          share|improve this answer


























          • Hi, as you can see in the codes I edited, I set the name when I create a new account. I'm not really sure when to use this AuthStateListener in my situation, as I know little about Firebase methods, could you show me?

            – C.Oli
            Nov 20 '18 at 15:33











          • search for Firebase AuthListener to setup a listener that will know when the current user is logged in or not, when it has signed out and more

            – Gastón Saillén
            Nov 20 '18 at 17:22














          0












          0








          0







          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.



          enter image description here



          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





          share|improve this answer















          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.



          enter image description here



          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






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 20 '18 at 15:29

























          answered Nov 20 '18 at 14:52









          Gastón SaillénGastón Saillén

          3,63341233




          3,63341233













          • Hi, as you can see in the codes I edited, I set the name when I create a new account. I'm not really sure when to use this AuthStateListener in my situation, as I know little about Firebase methods, could you show me?

            – C.Oli
            Nov 20 '18 at 15:33











          • search for Firebase AuthListener to setup a listener that will know when the current user is logged in or not, when it has signed out and more

            – Gastón Saillén
            Nov 20 '18 at 17:22



















          • Hi, as you can see in the codes I edited, I set the name when I create a new account. I'm not really sure when to use this AuthStateListener in my situation, as I know little about Firebase methods, could you show me?

            – C.Oli
            Nov 20 '18 at 15:33











          • search for Firebase AuthListener to setup a listener that will know when the current user is logged in or not, when it has signed out and more

            – Gastón Saillén
            Nov 20 '18 at 17:22

















          Hi, as you can see in the codes I edited, I set the name when I create a new account. I'm not really sure when to use this AuthStateListener in my situation, as I know little about Firebase methods, could you show me?

          – C.Oli
          Nov 20 '18 at 15:33





          Hi, as you can see in the codes I edited, I set the name when I create a new account. I'm not really sure when to use this AuthStateListener in my situation, as I know little about Firebase methods, could you show me?

          – C.Oli
          Nov 20 '18 at 15:33













          search for Firebase AuthListener to setup a listener that will know when the current user is logged in or not, when it has signed out and more

          – Gastón Saillén
          Nov 20 '18 at 17:22





          search for Firebase AuthListener to setup a listener that will know when the current user is logged in or not, when it has signed out and more

          – Gastón Saillén
          Nov 20 '18 at 17:22




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53395256%2ffirebase-getdisplayname-returns-empty%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to change which sound is reproduced for terminal bell?

          Can I use Tabulator js library in my java Spring + Thymeleaf project?

          Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents