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 storage using the image hash as a filename. I also maintain a Realtime Database that stores some information about the pictures. I need to select a random picture from the storage, so I decided to select a random entry from the database. I found this answer on SO (as you see, int is written in Javascript), which suggests the following code:
const numberOfUsers = 15;
const randomIndex = Math.floor(Math.random() * numberOfUsers);
var ref = firebase.database().ref('companies/01/users');
ref.limitToFirst(randomIndex).limitToLast(1).once('value').then(snapshot =>
{
var user = snapshot.val();
// do something with the user data
});
but when I try to build a similar query in Java
imgref.limitToFirst(random + 1).limitToLast(1).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
randomHash = dataSnapshot.getKey();
Log.e("get random name: ", randomHash);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
I recieve an error
Can't call limitToLast on query with previously set limit!
So obviously I cannot use limitToFirst and LimitToLast in one query. So here is my question:
Is it possible to use limitToFirst and limitToLast together somehow to use this method of getting a random entry?
Is there any other method to get a random entry from a Firebase Realtime Database without downloading the whole database or iterating through it (as far as I understand, iterating is inefficient, if I am wrong, please explain)
If it is impossible to do this from inside the app, is there some other way (for example, using Firebase Cloud Functions)