I'm working on an application in kotlin for sending an image to a random user or to multiple user from firebase. My database is structured like this :
- Users
- bVk3KBL81AY2LUVUbC6G1qcLAcl2
- username : test
- uid : bVk3KBL81AY2LUVUbC6G1qcLAcl2
- bVk3KBL81AY2LUVUbC6G1qcLAcl2
And I don't know how to get a random user from firebase, I searched but I don't find the best solution for my structure.
I try with this post : How to get unique random product in node Firebase?
But the code doesn't work I have multiple errors
Thank you in advance to any one who may be able to give me some solutions.
Edit #1 I've worked on it and it's working, but I don't know how limit the random to 3 users for example. In my application the user can change the limit of user so I need to change the random limit.
My code :
fun chooseRandomUser() {
val rootRef = FirebaseDatabase.getInstance().getReference()
val productsRef = rootRef.child("users")
val valueEventListener: ValueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val productList = ArrayList<String?>()
for (ds in dataSnapshot.children) {
val name = ds.child("username").getValue(String::class.java)
productList.add(name)
Log.d("FragmentActivity", "usernames : $name")
}
val productListSize = productList.size
val randomProductList = ArrayList<kotlin.Int>()
randomProductList.add(Random().nextInt(productListSize))
Log.d("FragmentActivity", "list : $randomProductList")
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d("FragmentActivity", "Error: ${databaseError.message}")
}
}
productsRef.addListenerForSingleValueEvent(valueEventListener)
}