1

I have this firebase database:

Firebase database

It stores candidates, who can be either president, secretary or treasurer (categories).

At the end of a voting period, I want to generate a report with who won, i.e, for President, check the candidate with the highest 'totalVotes' and get their name. it will be displayed as the winning candidate to the voters. Is it possible to do this? I have this code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
        DatabaseReference candidatesRef = rootRef.child("candidates");
        Query tatalVotesQuery = candidatesRef.orderByChild("tatalVotes").limitToLast(1);
        tatalVotesQuery.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot){
                for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                    highestpresident = childSnapshot.getKey();

                    System.out.println("President highest score is: " + highestpresident);
                    pres.setText(highestpresident);
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                throw databaseError.toException(); // don't swallow errors
            }
        });

1 Answers1

1

Is it possible to do this?

Sure, it is. The simplest solution for that would be to create a query and order the results like so:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference candidatesRef = rootRef.child("candidates");
Query tatalVotesQuery = candidatesRef.orderByChild("tatalVotes").limitToLast(1);

By default, the results are in ascending order. So the candidate with the highest number of votes will always be the last.

If you need to reorder them, please check my answer from the following post:

How to arrange firebase database data in ascending or descending order?

Edit:

According to your comment:

It gives a key and not the name of the candidate

It gives you the key because this is what you request. If you need the value for the first name and last name, please use the following lines of code:

String firstname = childSnapshot.child("firstname").getValue(String.class);
String lastname = childSnapshot.child("lastname").getValue(String.class);
pres.setText(firstname + " " + lastname);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193