I have an Android app using Google Firebase.
I need to download an image with a random ID.
I have a function that must return a Bitmap of the random picture. In this function I read the amount of pictures from a separate database entry and then I generate a random ID in the range from 1 to the amount of pictures. Here is the code:
Random rand = new Random();
DatabaseReference amountRef = dbref.child("amount");
amountRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
amount = dataSnapshot.getValue(Long.class);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
long random = rand.nextLong() % amount + 1;
The function later downloads an image and produces and returns a bitmap. The problem is that the Listener code is executed parallel to the other code and the line
long random = rand.nextLong() % amount + 1;
produces a divide by zero error, because the amount variable is not yet updated. I also cannot put all the code inside OnDataChange, because I need to return the bitmap. Please tell me how to retrieve the data immediately or return the bitmap from inside the listener.