Kotlin: How to get user Email/Username from firebase on Android

Viewed 813

I am creating a project whereby a user database is automatically created on signup for the first time. It functions well, however, i want the information on the database to display the User's Email or Name and not uid as shown below.

Image from firebase

the only reason i am using uid is because i have failed to successfully manage to call a function that enables me to display it.

here is my code:

they belong in an Object activity so the first 2 code examples are object codes

  1. initiate the firebase setup

    object FirestoreUtil {
    
     private val FirestoreInstance: FirebaseFirestore by lazy { FirebaseFirestore.getInstance() }
    
     private val currentUserDocRef: DocumentReference
       get() = FirestoreInstance.document(
         "users/${FirebaseAuth.getInstance().currentUser?.uid
             ?: throw NullPointerException("UID is null.")}"
       )
    

2.THIS is used on the signup button to create a new users database on launching;

 fun InitCurrentUserIfFirsttime(onComplete: () -> Unit) {
    currentUserDocRef.get().addOnSuccessListener { documentSnapshot ->

        if (!documentSnapshot.exists()) {
            val newUser = User(
                FirebaseAuth.getInstance().currentUser?.displayName ?: "",
                "", "",null, mutableListOf()
            )
            currentUserDocRef.set(newUser).addOnSuccessListener {
                onComplete()
            }
        }else{
                onComplete()

        }

    }
}

3.My data class;

data class User(val name: String,
             val bio: String,
             val age: String,
             val profilePicturePath: String?,
             val registrationTokens: MutableList<String>) {
constructor(): this("", "", "",null, mutableListOf())

}

4.from my signup button;

  auth.createUserWithEmailAndPassword(signuptv.text.toString(),  signupPassword.text.toString())
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                FirestoreUtil.InitCurrentUserIfFirsttime {
                    startActivity(Intent(this, LogInActivity::class.java))
                    finish()
                }

            } else {
                Toast.makeText(baseContext, "Authentication failed.",
                    Toast.LENGTH_SHORT).show()
            }

        }
0 Answers
Related