Kenan Jasim
Kenan Jasim

Reputation: 27

How to retrieve the latest data that has been pushed to a child in Firebase?

So I am still trying with my app and have run into another brick wall, I would like to retrieve the latest "bloodLevel" from this set of data that has been saved to firebase and output it to a textview and im not sure how I would do that:

"BGRatio" : "1",
  "CarbRatio" : "5",
  "Entries" : {
    "-KfcV3kfCMTcbeSa9Wv6" : {
      "BloodLevels" : "7.5",
      "Carbohydrates" : "20",
      "DateandTime" : "19 Mar 2017, 21:36:47",
      "Insulin" : "4.5"
    },
    "-KfcX05Fo2XDYLAkrBW-" : {
      "BloodLevels" : "14",
      "Carbohydrates" : "65",
      "DateandTime" : "19 Mar 2017, 21:45:17",
      "Insulin" : "20.0"
    },
    "-KfcrF6dKSolRl36dn4u" : {
      "BloodLevels" : "12",
      "Carbohydrates" : "90",
      "DateandTime" : "19 Mar 2017, 23:18:03",
      "Insulin" : "23.0"
    },
    "-Kfeqt1T27RKSNMkZrYA" : {
      "BloodLevels" : "24",
      "Carbohydrates" : "10000",
      "DateandTime" : "20 Mar 2017, 08:35:43",
      "Insulin" : "2017.0"
    },
    "-Kg4DU0eM8sx9uIHbDL4" : {
      "BloodLevels" : "13.3",
      "Carbohydrates" : "50",
      "DateandTime" : "Mar 25, 2017, 11:28:54 AM",
      "Insulin" : "16.3"
    },
    "-KgIxNJNSDpTAKpo62hn" : {
      "BloodLevels" : "8.0",
      "Carbohydrates" : "40",
      "DateandTime" : "Mar 28, 2017, 9:08:30 AM",
      "Insulin" : "9.0"
    },
    "-KgOJ-4eGU5z_dTuxfoq" : {
      "BloodLevels" : "10",
      "Carbohydrates" : "50",
      "DateandTime" : "Mar 29, 2017, 10:05:25 AM",
      "Insulin" : "13.0"
    }
  },
  "Ideal Level" : "7"
}

Any help on this would be great, thank you!!!

Upvotes: 0

Views: 243

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

You should be saving the DateandTime as a timestamp so that you can orderByChild('DateandTime') on it and then select the last one using limitToLast(1).

https://firebase.google.com/docs/reference/android/com/google/firebase/database/Query.html#orderByChild(java.lang.String) https://firebase.google.com/docs/reference/android/com/google/firebase/database/Query#limitToLast(int)

Upvotes: 2

Related Questions