0

My database (Firebase Realtime Database) looks like this:

here is the image

The code I wrote for sorting the orders acc. to Time:

val myRef = FirebaseDatabase.getInstance().getReference("Orders");
myRef.orderByChild("Time").addValueEventListener(orderListener)

But this won't work? I think my argument to orderByChild method is wrong. How to fix this?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • 1
    "But this won't work? I" Why not? It easiest to help if you show the code that reproduces your actual problem. Also see: [how to create a minimal, complete, verifiable example](http://stackoverflow.com/help/mcve). – Frank van Puffelen Aug 28 '21 at 23:31
  • The code looks fine. Can you also show us how you use it further and also what do you mean with "won't work". Do you get any data? Is it not sorted as expected? Consider also that you store the data as `String` and it will be sorted as a `String` data type and not as time or number. – Tarik Huber Aug 29 '21 at 08:35
  • Hadn't indexed the firebase database rules. Using .IndexOn made it work! Thanks anyways! :) – DevAbhinav Sep 08 '21 at 22:09

1 Answers1

0

In order to be able to get the data, you have to attach a listener on the Query object and iterate through the results as you can see in the following lines of code:

val rootRef = FirebaseDatabase.getInstance().reference
val ordersRef = rootRef.child("Orders")
val queryByTime = ordersRef.orderByChild("Time")
val valueEventListener = object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        for (ds in dataSnapshot.children) {
            val phone = ds.child("Phone").getValue(String::class.java)
            Log.d("TAG", phone)
        }
    }

    override fun onCancelled(databaseError: DatabaseError) {
        Log.d("TAG", databaseError.getMessage()) //Don't ignore potential errors!
    }
}
queryByTime.addListenerForSingleValueEvent(valueEventListener)

Since your "Time" property is of type String, you may not get the best results, since the ordering is done lexicographically:

So the best option the you have is to change the type of the field from String to a number.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193