Sharon
Sharon

Reputation: 3909

How do I order 'subdata' in Firebase?

I have a Firebase dataset with the following structure:

 coloursets
  - default
    - key
    - name
    - colours
      - black
        - key
        - name
        - hex code
        - order
      - white
        - key
        - name
        - hex code
        - order

'Order' is just a number. When I retrieve it from the database, I want to be able to get the colours in a particular order, specified by the 'order' field. Eg to get black and then white, I'll give 'black' the order '1', and 'white' the order '2'.

How do I use this to retrieve the data in order? Or is there a better way to do it?

I'm currently using this to retrieve it:

DatabaseReference mColourSetReference = FirebaseDatabase.getInstance().getReference()
                    .child("coloursets").child(this.key);
mColourSetReference.addListenerForSingleValueEvent(listener);

but there's no way to specify the order to retrieve the colours. It seems to default to reverse order, so currently it's getting white first, and then black.

I'm more used to MySQL, so can't get my head around this, and I couldn't find anything in the documentation.

Edit

Here's a screenshot of the relevant parts of the database:

enter image description here

Upvotes: 0

Views: 178

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

To order, try this:

DatabaseReference mColourSetReference = FirebaseDatabase.getInstance().getReference()
            .child("coloursets").child("colours");
Query queries=mColourSetReference.orderByChild("order");

public Query orderByChild (String path)

Create a query in which child nodes are ordered by the values of the specified path.

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

Upvotes: 1

Related Questions