I am a beginner on Firebase and I want to know the correct way on how to display random data from my database. I have this node called "Users" having this structure:
Users
|---- ISbxAeNkkIcTpeL8GNBx3CbxU7F2
| |
| |---- Username: "user1"
| |
| |---- Email: "example@gmail.com"
| |
| |---- Index: 1
|
|--- d3FvVpsDu6UIVLBdUWxRN8GWZQB2
|
|---- Username: "user2"
|
|---- Email: "example2@gmail.com"
|
|---- Index: 2
Since Firebase has no function to retrieve random data, I came up with this code: (simplified, not exactly the code)
for (int i = 1; i <= 20; i++) {
//generate a random index
int random = new Random().nextInt((totalUserCount - 1) + 1) + 1;
FirebaseDatabase.getInstance()
.getReference("Users")
.orderByChild("Index")
.equalTo(random)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
UserModel model = dataSnapshot.getValue(UserModel.class);
usersList.add(model);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
The code works but I wanted to know if this is the right practice since I think it is a bad practice to loop my queries. Also, I have seen several solutions to load the whole node and manage it client-side, but I do not want this because it will get slow once there are a lot of users.