I am trying to fetch data from firebase based on userId, when the user logged in I need to show his profile details based on its id but I am unable to fetch it. Any help?
auth = FirebaseAuth.getInstance()
databaseRef = FirebaseDatabase.getInstance().getReference("Users/")
databaseRef.addValueEventListener(object: ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
//I want first_name and all other details of users
Log.e("first_name", snapshot.child(uid).getValue(String::class.java))
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
CodePudding user response:
One problem is that you don't seem to initialize uid
anywhere. So that should be:
auth = FirebaseAuth.getInstance()
uid = auth.currentUser.uid
Also see the Firebase documentation on getting the current user.
Next is not necessarily a bug, but definitely an optimization you'll want to do. Right now you read the entire Users
node into your Android app, to then only get a value from /Users/$uid
. As you add more users to the database, this is not going to scale.
What you'll want to do instead, is only load the node for the current user from the database with:
databaseRef = FirebaseDatabase.getInstance().getReference("Users/")
var userRef = databaseRef.child(uid)
userRef.addValueEventListener(object: ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
Log.e("first_name", snapshot.getValue(String::class.java))
}
...