Firebase Child data is returning null. Kotlin Android Studio

Asked

Viewed 26 times

0

Eai personal!

I need to return the current user’s name and surname, registered in firebase. However, I have tried several implementations and none of them returns the result I want. In this last implementation, it returns as null and I can’t understand why. Someone can help me ?

That is the implementation.

val uid = FirebaseAuth.getInstance().currentUser!!.uid
    val rootRef = FirebaseDatabase.getInstance().reference
    val usersRef = rootRef.child("Users")

    val valueEventListener = object : ValueEventListener {
        override fun onDataChange(dataSnapshot: DataSnapshot) {
            for (ds in dataSnapshot.children) {
                val firstName = ds.child("firstName").getValue().toString()
                val lastName = ds.child("lastName").getValue().toString()
                Log.d("TAG", "Hello" + " " + firstName)
                Toast.makeText(this@MenuActivity, "Hello $firstName and $lastName", Toast.LENGTH_LONG).show()
                nameUser.setText(firstName)
            }
        }

        override fun onCancelled(error: DatabaseError) {
            Log.d("TAG", error.message().toString())
            Toast.makeText(this@MenuActivity, error.message().toString(), Toast.LENGTH_LONG).show()
        }
    }
    usersRef.child(uid).addListenerForSingleValueEvent(valueEventListener)

The structure in Firebase is like this, as image...

A estrutura no Firebase esta assim,

nameUser is where I want the user name to appear, is a textView.

inserir a descrição da imagem aqui

If anyone can help me out. I’m desperate haha, it’s for my tcc!!

  • delete this for and change to val user = dataSnapshot.getValue<User>(), and nameUser.text = user.firstName

  • Sorry buddy, I don’t get it. I remove the for and what’s inside it tbm ? how will he recognize Child ?: Could you please write the code ?

  • I got it here man!! Thanks so much for the help.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.