-1

I am working on an Android app, where I need to get a random object from firebase from a child? How to do it in java?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

2

This is how I would do it, assuming I had a child with n objects:

If I didn't know how the value of n, I would first do this in my listener to get the total number of objects:

                long n = dataSnapshot.getChildrenCount();

Then I would generate a random integer, i, between 0 and n. If you don't know how to do this, Google it.

Finally, I would get the ith item from the child:

            final ArrayList<MyObject> objects = new ArrayList<>();
            for (DataSnapshot child : children) {
                MyObject object = child.getValue(MyObject.class);
                objects.add(object);
            }
            MyObject objectToUse = objects.get(i);

"MyObject" should obviously be whatever class you're using.

Am I missing something? Is there a better way to do this? I'm pretty new to Android and very new to Firebase so take what I have to say with a big grain of salt haha.

Elizabeth
  • 88
  • 1
  • 6