0

This question is a follow up question from a previous post.

Is there anyway to order the results alphabetically? I'm looking for something like Query's orderByValue().

...

protected ArrayList<String> usernames = new ArrayList<>();

Firebase userRef = ref.child("users");
userRef.addListenerForSingleValueEvent(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        usernames.clear(); // Clear list before updating
        for (DataSnapshot child : dataSnapshot.getChildren()) {
            String username = (String) child.child("username").getValue();
            usernames.add(username);
            Log.v(TAG, usernames + "");
        }
...
Community
  • 1
  • 1
young_souvlaki
  • 1,886
  • 4
  • 24
  • 28
  • It very well might be and I apologize. I was thinking in terms of a Firebase method when I initially asked the question. – young_souvlaki Sep 12 '15 at 15:49
  • I only marked it as a duplicate, because the accepted answer is basically a link to that one. If you want to order by name in Firebase, you use `orderByChild('name')`: https://www.firebase.com/docs/android/guide/retrieving-data.html#section-queries (which at this stage I **highly** recommend that you read). Firebase doesn't have a descending sort though, so you'll have to do that client-side. – Frank van Puffelen Sep 12 '15 at 16:08
  • Yes I have been referencing those very helpful guides. The problem I had was that if I didn't use `orderByChild()` when defining the `Query queryRef` I would get an error. Since I needed to sort the value of `/users/uid/username` for each `uid` parent I stored (where `uid` is the Firebase generated `uid`), I couldn't have my `queryRef` access only one `username` parent. Maybe I am not storing user info appropriately? Or would `Query` actually access the `username` in each individual child of my `users` parent? Please let me know if I am being clear or if I you need additional info. – young_souvlaki Sep 12 '15 at 16:34
  • Try `ref.child("users").orderByChild('username'). addListenerForSingleValueEvent(...`. It'll work. – Frank van Puffelen Sep 12 '15 at 16:47
  • Okay that worked! Can you post it as an answer so I can mark it? Thanks for your patience. – young_souvlaki Sep 12 '15 at 18:26

1 Answers1

2

I believe you want Collections.sort(usernames) once you've read all of the children from the dataSnapshot.

How can I sort an ArrayList of Strings in Java?

Community
  • 1
  • 1
  • Exactly what I needed! Is there any way to organize alphabetically in **descending** order? – young_souvlaki Sep 11 '15 at 20:04
  • 1
    Collections.sort(username ,Collections.reverseOrder()); should do it. .sort will take another parameter that is a Comparator object representing the normal sort order, but backwards. – Chris Cullins Sep 11 '15 at 20:06