Search code examples
androidfirebasefirebase-realtime-databasefirebaseui

FirebaseListAdapter alphabetical order


In my Android app, I have a ListView with a FirebaseListAdapter that shows me my users, now I want the firebaseListAdapter to be sort in alphabetical order. How can I achieve this?

Code:

mListView = (ListView) findViewById(R.id.listView);

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");

FirebaseListAdapter<String> firebaseListAdapter = new FirebaseListAdapter<String>(
                        this,
                        String.class,
                        android.R.layout.simple_list_item_1,
                        databaseReference
                ){
                    @Override
                    protected void populateView(View v, String model, int position) {

                        TextView textView = (TextView) v.findViewById(android.R.id.text1);
                        textView.setText(model);

                    }
                };

mListView.setAdapter(firebaseListAdapter);

Solution

  • That depends on what the name is. If you store the users under their name (so that the name is the key):

    FirebaseListAdapter<String> firebaseListAdapter = new FirebaseListAdapter<String>(
        this,
        String.class,
        android.R.layout.simple_list_item_1,
        databaseReference.orderByKey()
    ){
    

    But if for example you have the name as a property called "name", you'd use:

    FirebaseListAdapter<String> firebaseListAdapter = new FirebaseListAdapter<String>(
        this,
        String.class,
        android.R.layout.simple_list_item_1,
        databaseReference.orderByChild("name")
    ){
    

    Finally: if you want to order by the single string value of the keys:

    FirebaseListAdapter<String> firebaseListAdapter = new FirebaseListAdapter<String>(
        this,
        String.class,
        android.R.layout.simple_list_item_1,
        databaseReference.orderByValue()
    ){