1

I'm building an Android application in which the user can track its weight and progress by inserting their weight (optional) AND/OR upload a picture (optional).

{
  "users" : {
    "5aHvYy5wTIVAAgdOEso0wr2woHS2" : {
      "firstName" : "Justin",
      "logs" : [ {
        "date" : "16/05/2018",
        "progressPicture" : "http://www.google.com/example.jpg",
        "weight" : 82.1
      }, {
        "date" : "17/05/2018",
        "progressPicture" : "http://www.google.com/example.jpg"
      }, {
        "date" : "18/05/2018",
        "weight" : 80.3
      } ]
    }
}

I have managed to get the latest log by ordering by key and limiting the result to 1, using the following code.

firebaseDatabase.getReference(USER_REFERENCE).child(firebaseAuth.currentUser?.uid).child(LOG_REFERENCE).orderByKey().limitToLast(1).

As can be seen from my JSON, a log doesn't necessarily have to have a weight value.

MY QUESTION: How can I adjust my query so that I'll retrieve my latest log (so 1 log only based on key) where there is a value for weight?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Caspar Geerlings
  • 1,021
  • 2
  • 10
  • 21
  • 1
    Firebase Database queries can only order/filter on a single property. In many cases it is possible to combine the values you want to filter on into a single (synthetic) property. E.g. `"hasWeight_date": "true_20180518"`. For an example of this and other approaches, see my answer here: http://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase – Frank van Puffelen May 17 '18 at 14:00

2 Answers2

1

You can add new entry called weight_log,which will be updated once new weight is recorded , you can do it easily with firebase functions that will be triggered on each /users/{userId}/weight_log/{iterationID} create event

Then you can use limitToLast(1) on the new path

Generally it is good practice to flattening your data structure

yarin
  • 543
  • 1
  • 5
  • 18
0

From reading the wiki you can only filter the data and check if there's a value for weight by adding a ValueEventListener() which will return a list of all the list where you have to loop through it and get you value

https://firebase.google.com/docs/database/android/lists-of-data#filtering_data

Nathanael Mkaya
  • 121
  • 3
  • 7