0

I am making a chat application and want to arrange user in users list from firebaseStore in alphabetical order. if new users register with the application, these users will be added to the list automatically and arrange in alphabetical order ( like A to B to C, ..). I try to search the answer but I don't find the solution to my issue. Can anyone help me with how to solve it?

Here is my java code in Userfragment.java:

recyclerView = view.findViewById(R.id.recycler_view);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    mUsers = new ArrayList<>();



    imageProfile = view.findViewById(R.id.profile_image);
    username = view.findViewById(R.id.username);

    storageReference = FirebaseStorage.getInstance().getReference("uploads");

    fuser = FirebaseAuth.getInstance().getCurrentUser();
   
    Query query = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid()).orderByChild("username");


    Collections.sort(mUsers, new Comparator<User>() {
        @Override
        public int compare(User lhs, User rhs) {
            return lhs.getUsername().compareTo(rhs.getUsername());
        }
    });

    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (isAdded()) {

                User user = dataSnapshot.getValue(User.class);
                username.setText(user.getUsername());
                if (user.getImageUrl().equals("default")) {
                    imageProfile.setImageResource(R.mipmap.ic_launcher);
                } else {
                    Glide.with(getContext()).load(user.getImageUrl()).into(imageProfile);
                }
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

export Json file

below is some users in realtime database which I want to arrange:

Users 7HMH8nj6AshgYtvD2IMT9a7y2273
id "7HMH8nj6AshgYtvD2IMT9a7y2273" imageUrl "default" search "tony" status "online" username "Tony" AY3gY1eQE1fWJiNUsxxRqpXHBFf2
id "AY3gY1eQE1fWJiNUsxxRqpXHBFf2" imageUrl "default" search "hola" status "offline" username "hola" O6gRe8muq4TGDjQsYkn9Cdpufdy1
id "O6gRe8muq4TGDjQsYkn9Cdpufdy1" imageUrl "default" search "chon" status "offline" username "chon" SGQwWbIZ2vhkPcKqjMuejusKRY13
id "SGQwWbIZ2vhkPcKqjMuejusKRY13" imageUrl "default" search "miko" status "offline" username "miko"

Mr Tony
  • 19
  • 4
  • What is the problem with the code you shared. Specifically: if you step through it line by line in a debugger and check each variable on each line, what is the first line where you don't get the value that you expect? – Frank van Puffelen Jul 02 '22 at 02:26
  • It really isn't clear what you're asking, but.. you mentioned something vaguely about wanting to sort something, there's an `ArrayList` called "mUsers", so I'm making a leap that you want to sort "mUsers". If that's the case, take a look at: [Sorting arraylist in alphabetical order (case insensitive)](https://stackoverflow.com/questions/5815423/sorting-arraylist-in-alphabetical-order-case-insensitive) (or a number of other posts relating to sorting an `ArrayList` using a custom comparator). – Kaan Jul 02 '22 at 03:05
  • I try using the suggestion from you but it can't solve my issue. – Mr Tony Jul 02 '22 at 04:20

2 Answers2

0

Try this

FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("username");

Learn more here

Gobu CSG
  • 653
  • 5
  • 7
0

You're getting the following error:

java.lang.ClassCastException: com.google.firebase.database.Query cannot be cast to com.google.firebase.database.DatabaseReference

Because of the following line of code:

reference = (DatabaseReference) FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid()).orderByChild("username");

And this is because you are trying to cast an object of type Query to an object of type DatabaseReference, which is actually not possible in Java. The inheritance relationship is as follows, DatabaseReference extends Query and not the opposite.

To solve the problem, you should remove the cast to DatabaseReference and set the type of the object to be Query:

Query query =  FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid()).orderByChild("username");
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Thanks Alex Mamo for your guideline. the errors above disappear when I executive your code. Unfortunately, userlist still arrange disorder. there is no change in alphabetical order. Can you please give me other solution? – Mr Tony Jul 07 '22 at 06:18
  • What do you mean by "arrange disorder"? Please edit your question and add your database structure as a JSON file. You can simply get it by clicking the Export JSON in the overflow menu (⠇) in your [Firebase Console](https://console.firebase.google.com/u/0/project/_/database/data). – Alex Mamo Jul 07 '22 at 07:57
  • I mean user list appear not follow alphabetical order like A to B to C. – Mr Tony Jul 07 '22 at 09:33
  • In that case, as requested before, please edit your question and add your database structure as a JSON file. You can simply get it by clicking the Export JSON in the overflow menu (⠇) in your [Firebase Console](https://console.firebase.google.com/u/0/project/_/database/data). – Alex Mamo Jul 07 '22 at 09:35
  • Yes, I exported JSON file from Firebase console and what will I do next? if new user arise in the future do the new users will be automatically arranged in alphabetical order with old users? – Mr Tony Jul 07 '22 at 15:19
  • 1
    Add it to your question, so we can see it. We see what we can do, after we see the schema. – Alex Mamo Jul 07 '22 at 15:58
  • yes, I updated information my question – Mr Tony Jul 08 '22 at 02:14
  • No, please edit your question and add **your database structure** as a JSON file. You can simply get it by clicking the Export JSON in the overflow menu (⠇) in your [Firebase Console](https://console.firebase.google.com/u/0/project/_/database/data), or at least as a screenshot. – Alex Mamo Jul 08 '22 at 06:22
  • I clicked the Export JSON in Firebase Console at menu (⠇) and it create JSON file to save my computer. I don't know what to do with this file? I don't what to do with this file. – Mr Tony Jul 08 '22 at 06:30
  • Simply open it, and add the content to your question. – Alex Mamo Jul 08 '22 at 06:55
  • do I have to copy all content of this Json file and paste to my question? there are a lot data inside it. – Mr Tony Jul 08 '22 at 09:06
  • No, only a few children, to see what it looks like. Ok? – Alex Mamo Jul 08 '22 at 09:38
  • Yes, I edited my question and add some children of user information in Firebase. I am newbie if you need something else, please tell me. Thanks for your great patient with my question. – Mr Tony Jul 08 '22 at 14:13
  • Have you also tried to use this query, `Query query = FirebaseDatabase.getInstance().getReference("Users").orderByChild("username");` and iterate through the results? – Alex Mamo Jul 08 '22 at 14:16
  • Yes, I tried and posted that code in my question. the result is not changed – Mr Tony Jul 09 '22 at 01:47
  • Have you solved the issue? – Alex Mamo Jul 14 '22 at 05:03
  • the issue has not yet solved, sir – Mr Tony Jul 15 '22 at 09:13