Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve data from a Firebase database with Kotlin?

This is the model I upload on Firebase:

public class OnlineMatch{

private User user1;
private User user2;

public OnlineMatch(User firstPlayer, User secondPlayer) {
        this.user1 = firstPlayer;
        this.user2 = secondPlayer;
    }

}

Then I send data to Firebase in this way (kotlin):

 fun createMatch(match: OnlineMatch) {
        val matchList = database.child("multiplayer").push()
        matchList.setValue(match)
    }

Thus, my DB structure is the following:

enter image description here If I expand a node I can see perfectly my objects: OnlineMatch(User1, User2)

Now I would like to query the db and obtain an ArrayList'<'OnlineMatch'>'. I have already found the Firebase docs but I found nothing useful. How can I do? Thanks in advance.

like image 819
Giacomo Bartoli Avatar asked Oct 18 '22 08:10

Giacomo Bartoli


1 Answers

You did not find something useful because when you query against a Firebase database you get a Map and not ArrayList. Everything in Firebase is structured as pairs of key and value. Using an ArrayList is an anti-pattern when it comes to Firebase. One of the many reasons Firebase recommends against using arrays is that it makes the security rules impossible to write.

In Kotlin there is no need for getters and setters. Is true that behind the scenes those functions exists but there is no need to explicitly define them. To set those fields, you can use the following code:

val onlineMatch = OnlineMatch() //Creating an obect of OnlineMatch class
onlineMatch.user1 = userObject //Setting the userObject to the user1 field of OnlineMatch class
//onlineMatch.setUser(userObject)

As you probably see i have commented the last line because there is no need to use a setter in order to set a userObject.

And very important, don't forget to add the no argument constructor in your OnlineMatch class that is needed for Firebase.

public OnlineMatch() {}

Edit:

To actually get the data, just put a listener on the desired node and get the data out from the dataSnapshot object into a HashMap.

val map = HashMap<String, OnlineMatch>()

Then simply iterate over the HashMap like this:

for ((userId, userObject) in map) {
    //do what you want with them
}

Or simply use the code below:

val rootRef = firebase.child("multiplayer")
rootRef.addListenerForSingleValueEvent(object : ValueEventListener {
    override fun onCancelled(error: FirebaseError?) {
        println(error!!.message)
    }

    override fun onDataChange(snapshot: DataSnapshot?) {
        val children = snapshot!!.children
        children.forEach {
            println(it.toString())
        }
    }
})

Hope it helps.

like image 83
Alex Mamo Avatar answered Oct 21 '22 01:10

Alex Mamo