Home > Net >  How can I get username from real time database and show it in navigation header?
How can I get username from real time database and show it in navigation header?

Time:04-01

enter image description here

Register Button in Register Acvtivity

public void registerBtnClicked(View view){

    String email = binding.userEmailEditText.getText().toString();
    String password = binding.userPasswordEditText.getText().toString();
    String userNameData =  binding.usernameEditText.getText().toString();

    user = new Users(userNameData,email,password);
    db = FirebaseDatabase.getInstance();
    databaseReference = db.getReference(Users.class.getSimpleName());
    databaseReference.push().setValue(user);


    if(email.equals("") || password.equals("")){
        Toast.makeText(this, "Enter email and password", Toast.LENGTH_LONG).show();
    }else{
        auth.createUserWithEmailAndPassword(email,password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
            @Override
            public void onSuccess(AuthResult authResult) {
                Intent intent = new Intent(RegisterPage.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(RegisterPage.this, e.getLocalizedMessage(),Toast.LENGTH_LONG).show();
            }
        });
    }

}

I created a real time database.But I couldn't figure out how to show username in navigation header section. Can you help me?

CodePudding user response:

If I understand correctly, the firebaseUser is null when you're trying to read the display name from it. This is actually a common scenario, as the user's sign-in session is managed by Firebase in the background, and the current user may change at any time.

The simple fix is to check whether there is a current user before accessing their display name, which you can do with:

firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
    navUserEmail.setText(firebaseUser.getEmail());
    navUserName.setText(firebaseUser.getDisplayName());
}

Note though that the display name is an optional property of the user profile, so it can indeed be null. If you want to display nothing in that case, you can do:

String displayName = firebaseUser.getDisplayName();
navUserName.setText(displayName != null ? displayName : "");

Even if you've set the display name of a user, it may take up to an hour until that is updated for all connected clients, as they all cache the user profile. And since such updates happen in the background...

  • Related