0

I have an Android Firebase with a section that contains a list of objects (numbered 1 to ~500). I am working on a code that selects six of these objects at random and returns them as a list. I have it working, but I am convinced that it is a very inefficient method. I currently generate a list of six random integers and use addListenerForSingleValueEvent six separate times to pull each object.

Is it possible to simplify this and build a HashMap so that I have one listener that pulls all six objects as a list?

I am currently using the method below. I call it six times (once for each random number), set a DatabaseReference based on the passed random integer, and add the return value to a list.

    private void getRandomObject(int objectIdNumber){
    DatabaseReference objectRef = baseRef.child(Constants.FB_LOCATION_OBJECTS)
            .child(Integer.toString(objectIdNumber));

    objectRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            System.out.println(snapshot.getValue());

            //The list below is the global ArrayList<Object> 
            objectOptionsList.add(snapshot.getValue(POJOObject.class));
            numberOfObjectsToGet--;
            if (numberOfObjectsToGet == 0) {
                proceed();
            }
        }

        @Override
        public void onCancelled(DatabaseError firebaseError) {
            System.out.println("The read failed: " + firebaseError.getMessage());
        }
    });
}
aterbo
  • 432
  • 7
  • 24
  • 1
    What you're looking for boils down to a SQL `WHERE id IN [4, 8, 15, 16, 23]`. Firebase doesn't have such an operation, since it is not significantly more efficient than loading them wth a loop. For why that is, see [my answer here](http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786). – Frank van Puffelen Jun 12 '16 at 14:54
  • Thanks, @FrankvanPuffelen! I checked my logic, and I'm calling the above getRandomObject method by looping through all six random numbers and calling the method six times in a row. The app only moves on once the onDataChange function is triggered six times (tracked with numberOfObjectsToGet). It looks like I'm inadvertently already following the parallel processing outlined in your other answer, so I'm glad to know that my hack and slash solution ended up being acceptable :) – aterbo Jun 12 '16 at 17:46

0 Answers0