0

I have an android app that is connected to a Firebase cloud database. For a given user, the database stores a list of Reservation objects.

I followed Google's guidelines to store reservations into the database:

private void addReservation() {
    reservations = users.child(mReservation.getUserId()).child(KEY_RESERVATIONS);
    reservations.push().setValue(mReservation);
}

The push is successfully saved and my JSON data for a given user has the following format:

 {
      "email" : "fake.email@fake.com",
      "reservations" : {
        "-KMTRX1cOAu3v_pN1GHs" : {
          "date" : "01/07/2018",
          "formattedDate" : "01//0/7/2018",
          "formattedSlot" : "10:/0",
          "massage" : "Back massage",
          "price" : 60,
          "promoCode" : false,
          "slot" : "10:00",
          "userId" : "YD7uQGwApLe5Xi90BSGQhcOqSk32"
        }
      }
    }

When I launch a "ReservationsActivity", I load a list of reservations from the database using this function:

        if (userHasReservations(dataSnapshot)) {
            DataSnapshot snapshot = dataSnapshot.child(currentUser.getUid()).child(KEY_RESERVATIONS);

            List<Reservation> userReservations = snapshot
                    .getValue(new GenericTypeIndicator<ArrayList<Reservation>>() {});
  }

But I get a Database error. The function expected a map:

DatabaseException: Expected a List while deserializing, but got a class java.util.HashMap

According to Google's documentation, if you store elements using the push method, you can then retrieve them as a list. However, I keep running into this mistake.

Can you help me to figure this out?

Thank you very much.

  • It seems like you are getting a reference to your root node and adding an `EventListener` to that. Its better that you get a reference to the node of the particular user's reservations node and add a `ChildEventListener` to it. This way, you wont download your whole database. In your `ChildEventListener`, you can call `arrayList.add(dataSnapshot.getValue(Reservation.class));` – Rohit Navarathna Jul 12 '16 at 09:56
  • That is what I was trying to avoid. I'd like to get all reservations from a single call to avoid the extra overhead. But if there is no other way, I guess I will have to do it 1 by 1. Thank you very much for your help! – Javier Ventajas Hernández Jul 12 '16 at 10:07
  • even then you should add a `ValueEventListener` to your "userid/reservations" node and not the root. Adding it to the root will download the reservations of all the users everytime one is updated – Rohit Navarathna Jul 12 '16 at 10:27
  • What you have in your database is a `Map`, not a `List`. So you will need to read it as a `Map` and then get yours list of values using `map.value()`. See http://stackoverflow.com/questions/32886546/how-to-get-all-child-list-from-firebase-android/32888869#32888869 – Frank van Puffelen Jul 12 '16 at 14:02

0 Answers0