Skip to content Skip to sidebar Skip to footer

Select Random Entry From Firebase Realtime Database In Java

I am developing an application for Android that involves uploading and downloading images to a server. I am using Firebase for this purpose. All the images are stored in Firebase s

Solution 1:

If you aren't against adding an extra child to your data, you have a few options.

  1. You could use a transaction to number each item when they are added, then use a random number with startAt(random).limitToFirst(1).
  2. If you want to avoid the transaction you could write a random long to each imgref node. Then you could try querying with a newly generated random like this:

    ref.orderByChild("randomLong").startAt(newRandomLong).limitToFirst(1).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.getChildrenCount() > 0){
                for(DataSnapshot snap : dataSnapshot.getChildren()){
                    //Do something with your random snapshot
                }
            }else
            {
             /*
             Handle case where the new random Long is after the range 
             currently in the database
             ref.orderByChild("randomLong").endAt(random).limitToLast(1)
             */
            }
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
    
        }
    });
    

Note that #2 will add random weights to your values based on the random ranges between values. This effect should be less noticeable on larger lists, but if you need an even distribution you probably want to go with option #1.

If you can't change your current data structure then I'm not sure you can get around iterating the set as in Alex's answer.

Solution 2:

You need to know how is your model to get a random key. If it is 1,2,3,4,5 ids you can use it like you are doing, so you can compare it. The best way to do it, is to store all key values in a array, pick a random number with the array size and pick the index of the random number. Them u use the code from the similar answer dataSnapshot.getKey();

Post a Comment for "Select Random Entry From Firebase Realtime Database In Java"