firebasefirebase-realtime-databasekotlindata-retrievalauto-populate

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.


Solution

  • 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.