Ali Ahmed
Ali Ahmed

Reputation: 2455

How to get data from firebase ( datasnapshot)?

I am using firebase database and I had stored the user information in the database ( realtime ) and I want to get the information into my user profile UI in my app Now when I use snapshot, I don't know how to get the information of it Any help please?

        val userId = authRef.currentUser?.uid
        val currentUser = dataRef.getReference("/Users/$userId")
        currentUser.addValueEventListener(object : ValueEventListener{
            override fun onCancelled(p0: DatabaseError) {

            }

            override fun onDataChange(p0: DataSnapshot) {
//    I need to get data from here ( userDisplayName , userPhone, userCity, userCountry)
        }

        })

Upvotes: 0

Views: 589

Answers (2)

DikShU
DikShU

Reputation: 96

Try this

 val userId = authRef.currentUser?.uid
    val currentUser = dataRef.getReference
    val userchild = currentuser.child("Users").child("userId")
    userchild.addValueEventListener(object : ValueEventListener{
        override fun onCancelled(p0: DatabaseError) {

        }

        override fun onDataChange(p0: DataSnapshot) {
            val userDisplayName = p0.child("userDisplayName").getValue(String::class.java)
    val userPhone = p0.child("userPhone").getValue(String::class.java)
    val userCity = p0.child("userCity").getValue(String::class.java)


    }

    })

Must type exect spellings of Users, UserId and other childs. and To these values to textview in the Ui add

 TextView.setText=variable abc

Your Mistakes in codes.You have not taken correct data snapshot which i have updated.

Upvotes: 1

Peter Haddad
Peter Haddad

Reputation: 80914

To retrieve the data try the following:

override fun onDataChange(p0: DataSnapshot) {
//    I need to get data from here ( userDisplayName , userPhone, userCity, userCountry)
        val userDisplayName = p0.child("userDisplayName").getValue(String::class.java)
        val userPhone = p0.child("userPhone").getValue(String::class.java)
        val userCity = p0.child("userCity").getValue(String::class.java)

        }

        })

Upvotes: 1

Related Questions