How to get the grandchildren from a list of children of a parent node in Firebase?

0

I am currently working with Firebase and Android. I am trying to make a rating system for a list of restaurants but I have found a detail, I do not know how I can get the grandchildren from a list of children of a parent node and then take the average of each restaurant.

The parent node refers to the container of the ids of each Restaurant, inside I have a list of the qualifications of the users of that Restaurant and I am trying to obtain all the qualified restaurants with their qualifications and to attach the results in a RecyclerView but I do not know how to do it correctly.

SOLUTION

I do not know if it is the most efficient solution but I managed to make it work, what I did was create two variebles List < > and a HashMap < >.

The first List < > to store the basic information of the Restaurant (Id, Name, Specialty, etc ...), the HashMap < > to store the ( id ) of each Restaurant as the key and the ( rating ) as the value and the last variable List ; to gather all the information in a single list and then pass it to the RecyclerView. (For this, also create 3 POJO classes)

calculate the average

Function to gather all the information

The node in the database in Firebase changes it and it looks like this:

    
asked by Sergio94 02.09.2018 в 19:10
source

1 answer

0

To get all the ratings below the parent node data podes do the following

first we create a class with the data that you want to bring, they have to have the same name as in firebase and data type.

RestaurantPojo.class

public class RestaurantPojo{

    private int rating;

    public RestaurantPojo(){

    }


    public int getRating() {
        return rating;
    }

    public void setRating(int rating) {
        this.rating = rating;
    }


}

Then we only ask for the data once from all the restaurants

mDatabase.child("Ratings").child("data").addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    //Recorremos todos los hijos debajo de data y obtenemos los ratings
    for(DataSnapshot snapshot: dataSnapshot.getChildren()){
    RestaurantPojo rp = snapshot.getValue(RestaurantPojo.class);
    //Obtenemos los valores que queres
     int rating = rp.getRating();
     //Para obtener el padre que contiene cada rating podes hacer lo siguiente 
     String padre = snapshot.getKey();

      Log.e("Datos: " , "" + rating);

       }

  }

  @Override
  public void onCancelled(DatabaseError databaseError) {
    System.out.println("The read failed: " + databaseError.getCode());
  }
});

Where mDatabase is

DatabaseReference mDatabase;

mDatabase = FirebaseDatabase.getInstance().getReference();
    
answered by 02.09.2018 в 19:44