Reputation: 876
Edit
I have a firebase database with a tree that looks like this
Stations{
Uknradio
bbcradio1
bbcradio1extra
Beatles radio
then a StationsKey node that looks like this
Stations{
Uknradio = true
bbcradio1 =true
bbcradio1extra = true
Beatles radio = true
and so on... id like to pull a random station from the database
here is the code im working with which is the new answer given
String DATABASE_CHILD = "STATIONS";
String DATABASE_CHILD2 ="STATIONKEY";
ref = db.getReference().child(DATABASE_CHILD2);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
String productId = ds.getKey();
productIdsList.add(productId);
}
int productListSize = productIdsList.size();
ref = db.getReference().child(DATABASE_CHILD).child(productIdsList.get(new Random().nextInt(productListSize)));
ref2.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
mUrl.clear();
mTITLE.clear();
mDOWN.clear();
mIMAGE.clear();
mUrl.clear();
mUP.clear();
mDESC.clear();
for (DataSnapshot snap : snapshot.getChildren()) {
station_items = snap.getValue(Stations_Firebase.class);
String a =station_items.getStation();
String b = station_items.getTag();
String c = station_items.getUrl();
Long d = station_items.getUpvote();
Long e = station_items.getDownvote();
String f = station_items.getImage();
mTITLE.add(a);
mDESC.add(b);
mUrl.add(c);
mUP.add(String.valueOf(d));
mDOWN.add(String.valueOf(e));
mIMAGE.add(f);
}
private int nextInt(int productListSize) {
return 0;
}
but now im getting this error
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.p9p.radioify.ui.station_tabs.Random.getRandomStations(Random.java:103)
Upvotes: 4
Views: 2611
Reputation: 1
Edit: 20th, August 2022
Maybe these other approaches will help:
To solve this, please use the following lines of code:
long childrenCount = snapshot.getChildrenCount();
int count = (int) childrenCount;
int randomNumber = new Random().nextInt(count);
And then use a for
loop to pull that value using the random number:
int i=0;
String themeTune; //Your random themeTune will be stored here
for (DataSnapshot snap : snapshot.getChildren()) {
if(i = randomNumber) {
themeTune = snap.getValue(String.class);
break;
}
i++;
}
plysound();
Upvotes: 7