Get random entries in firebase real-time database

2019-08-20 00:02发布

问题:

This is my code to get 5 items from realtime database:

val database = FirebaseDatabase.getInstance()
val brandReference = database.getReference("brandGame").limitToFirst(5)
brandReference.addValueEventListener(object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
         dataSnapshot.children.forEach {
            ...
         }
    }
}

And this is how my real-time database looks like:

What's the best way to get 5 items randomly? I know there isn't a random function in real time database yet.

回答1:

If you know the number of elements in the brandGame/-reference, you could pick 5 random numbers between 1 and numberOfElements and retrieve those. This would result in multiple calls to the database.

Alternatively, you could download everything from the brandGame/-reference and just pick 5 random elements using pure Kotlin. But then you must download everything in the reference, which could be a lot.

The best option is to set up a cloud function that does the "pick 5 random options"-logic server side. https://firebase.google.com/docs/functions/ But this requires that you write some js :)

As you say, there is no built-in way to get random elements from a reference.



回答2:

To get a random brand, please use the following code user side:

val rootRef = FirebaseDatabase.getInstance().reference
val brandGameRef = rootRef.child("brandGame")
val valueEventListener = object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        val brandCountList = ArrayList<String>()
        for (ds in dataSnapshot.children) {
            val brand = ds.child("brand").getValue(String::class.java)
            brandCountList.add(brand!!)
        }

        val brandCount = brandCountList.size
        val randomNumber = Random().nextInt(brandCount)

        val randomBrand = ArrayList<String>()
        randomBrand.add(brandCountList.get(randomNumber)) //Add the brand product to list

        val arrayAdapter = ArrayAdapter(applicationContext, android.R.layout.simple_list_item_1, randomBrand)
        list_view.adapter = arrayAdapter
    }

    override fun onCancelled(databaseError: DatabaseError) {
        //Handle exceptions
    }
}
brandGameRef.addListenerForSingleValueEvent(valueEventListener)