Search code examples
androidfirebaseandroid-studiofirebase-authenticationonstart

Why firebaseuser.getdisplay name is returning something even it doesn't contain a name?


Here is my onStart method I want to open an activity when user has updated his profile name

@Override
protected void onStart() {
    super.onStart();
    FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    if (firebaseUser != null) {
        if (firebaseUser.getDisplayName() == null) {
            startActivity(new Intent(WorkerMaps.this, FirstWorkerInformation.class));
            finish();
        }
    }

}

Solution

  • First, nowhere in the question have you mentioned your actual problem.

    Hence, what your problem is that even if the displayName() doesn't contain a name, it still returns something which is not null.

    Hence, what you can do for that is modify your code and use isBlank() as this.

    if (firebaseUser.getDisplayName() == null || firebaseUser.getDisplayName().isBlank()) {

    Now, what this will do that it will also check if your displayName only containts spaces and no characters and if true, it will enter in your if scope.

    You can read more about isBlank() here.

    Update: Because isBlank() is a part of StringUtils and that's a separate library provided by Apache, You can import that library as answered here.

    But if you don't want to use a separate library, you can also use trim() which removes spaces from a string's starting and ending point as:
    " Name " -> "Name"
    " " -> ""

    So, what you can do with it, you can check its length and if it's 0, then it will return true as in case of " ". You can do it as:

    if (firebaseUser.getDisplayName() == null || firebaseUser.getDisplayName().trim().length() == 0){