Query Random Nodes from Firebase RealTime Database

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) {

}
});
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

--

--

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