Query Random Nodes from Firebase RealTime Database

While building my app ( Revivan -A Travel Machine via Quotes ), I needed to query random nodes from the Firebase Database whenever the user refresh the layout, but Firebase doesn’t provide such a function for queries yet .

In order to achieve that, I had first to edit my Database nodes by adding a random index to each item.

FirebaseDatabase.getInstance().getReference().child("#your_node_path").runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
long max = mutableData.getChildrenCount();
for (MutableData data : mutableData.getChildren()) {
Node node = data.getValue(Node.class);
if (node!= null ) {
node.index = (int)(Math.random() * max +1);
data.setValue(node);
}
}
return Transaction.success(mutableData);
}

@Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {

}
});

PS: Don’t forget to add the index member to your Data Class also .

After finishing this step, using the Firebase provided functions for a query it will be so simple to Query random item/s . All what you need is generate a random number and use orderByKey() and limitToLast() and limitToFirst() provided functions.

int startIndex = (int)(Math.random() * MAX +1);
query = FirebaseDatabase.getInstance().getReference()
.child("#your_nodes_path")
.orderByChild("index")
.startAt(startIndex)
.endAt(startIndex + 4); //querying 4 random items

And here you have your query of random nodes :D .

Any questions or recommendation for better implementation please feel welcome to leave a comment ;) .

Full Stack Developer| Loading…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store