How get random child from firebase database?

Viewed 142

i try to get random child from my firebase. but i cant, i was try from many idea from stackoverflow too but still not working. for example, i want get random child from "Bahan Makanan Susu", and after get a random child i want show the value of "kalori".

This my database created

enter image description here

this my currently code

reff = FirebaseDatabase.getInstance().getReference();
reff.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull  DataSnapshot dataSnapshot) {
        String Sskal =dataSnapshot.child("Bahan Makanan Susu").child("3").child("Kalori").getValue().toString();

'child("3")' in here i create manually and i want to make it random. thankyou hope u all can help me

2 Answers

Try this:

reff = FirebaseDatabase.getInstance().getReference("Bahan Makanan Susu/3/Kalori");
reff.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull  DataSnapshot dataSnapshot) {
        String Sskal = dataSnapshot.getValue().toString();
        Log.i("Firebase", Sskal);
    }
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) { 
        throw databaseError.toException(); 
    }
}

The main changes and points to pay attention to:

  • This code reads only property from the database, passing in the entire path to that node/property in to getReference.
  • Always implement onCancelled as it can point out access problems for your database. If you get an exception for this, search for the error message to learn how to deal with it.
  • If this also doesn't read any value, you've never been able to read or write to the database, and your database is in another region than the US, consider re-downloading your google-services.json file, or specifying the database URL in the getInstance("URL here") call in your code.
  • You really shouldn't use sequential numeric keys like this. They're an anti-pattern in Firebase, as the SDKs try to interpret them as arrays. For more on this, see Best Practices: Arrays in Firebase.

Try this:

reff = FirebaseDatabase.getInstance().getReference();
reff.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull  DataSnapshot 
dataSnapshot) {
        Random r = new Random();
        int total = reff.child("Bahan Makanan Susu").getChildrenCount();
        String Sskal =dataSnapshot.child("Bahan Makanan 

Susu").child(r.nextInt(total)).child("Kalori").getValue().toString(); });

You would have to do a check everytime though so one child doesn't get repeated but I hope you will be able to make it work.

Related