Dimitri Hartt
Dimitri Hartt

Reputation: 1871

Retrieve data with child from Firebase Database and Populate Object Class using Kotlin

How can I retrieve data with child* from Firebase Database and populate an User object class.

Firebase example:

and after having retrieved the data being able to use ie.: User.firstName or User.location.lat etc.

Thank you in advance.

Upvotes: 1

Views: 3665

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

As Sam Stern mentioned in his answer, it's best to create a representation for each class separately. I'll write you the corresponding classes in Kotlin.

This is the User class:

class User (
    val firstName: String = "",
    val lastName: String = "",
    val userLocation: UserLocation? = null
)

And this is the UserLocation class:

class UserLocation (
        val lat: Int = 0,
        val lng: Int = 0
)

to query this User 1332 and cast it to the User.class object

Please use the following lines of code:

val uid = FirebaseAuth.getInstance().currentUser!!.uid
val rootRef = FirebaseDatabase.getInstance().reference
val uidRef = rootRef.child("users").child(uid)
val valueEventListener = object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        val user = dataSnapshot.getValue(User::class.java)
        Log.d(TAG, "Lat/Lng: " + user!!.userLocation!!.lat + ", " + user.userLocation!!.lng);
    }

    override fun onCancelled(databaseError: DatabaseError) {
        Log.d(TAG, databaseError.message) //Don't ignore errors!
    }
}
uidRef.addListenerForSingleValueEvent(valueEventListener)

In which the uid should hold a value like 131232. The output in your logcat will be:

Lat/Lng: 15.2512312, -12.1512321

In the same way you can get: user!!.firstName and user!!.lastName.

Upvotes: 2

Sam Stern
Sam Stern

Reputation: 25134

Your best bet is to create multiple custom classes:

class User {
  public String firstName;
  public String lastName;
  public UserLocation location;
}

...

class UserLocation {
   public double lat;
   public double lon;
}

Then you can deserialize the whole thing to User.

Upvotes: 1

Related Questions