0

Here is my database:

Firebase database

For each category, it is supposed to return the candidate with the highest 'totalvotes'.

Here is my code:

Query presidentquery = reference.child("candidates").orderByChild("category").equalTo("President");
        presidentquery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                        String firstname = dataSnapshot1.child("firstname").getValue(String.class);
                        String lastname = dataSnapshot1.child("lastname").getValue(String.class);
                        Long tvotes = dataSnapshot1.child("totalVotes").getValue(Long.class);
                        pres.setText(firstname + " " + lastname+" - "+tvotes+" Votes");
                    }
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });

Instead of returning the candidate with highest votes, it returns the most recent candidate. How can I filter the results in datasnapshot to display the candidate with highest 'totalVotes'.

Thanks

  • Have you check this one https://stackoverflow.com/a/41459836/9346054? – Ticherhaz FreePalestine Apr 09 '20 at 01:41
  • Cant get it to work. I seem to be dealing with a query within a query. – Ngugi Kariuki Apr 09 '20 at 01:53
  • Firebase Database queries can only order/filter on a single property. In many cases it is possible to combine the values you want to filter on into a single (synthetic) property. For an example of this and other approaches, see my answer here: https://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase – Frank van Puffelen Apr 09 '20 at 02:44
  • Have you answered a java question like this before you point me to it please? I am not very good at javascript and the above answer deals with javascript. – Ngugi Kariuki Apr 09 '20 at 02:53

1 Answers1

1

I replicated your issue and found out a way to obtain the candidate with the highest number of votes.

Add the below method in your model class.

@Override
    public int compareTo(Candidate o) {
        return (this.getTotalVotes() > o.getTotalVotes() ? -1 :
                (this.getTotalVotes() == o.getTotalVotes() ? 0 : 1));
    }

To override the compareTo method, you need to implement Comparable class by implements Comparable<Candidate>

Create a class to sort the values

public class Sorter {

    ArrayList<Candidate> candidateList = new ArrayList<>();
    public Sorter(ArrayList<Candidate> candidateList) {
        this.candidateList = candidateList;
    }
    public ArrayList<Candidate> sortByTotalVotes() {
        Collections.sort(candidateList);
        return candidateList;
    }

}

In your Activity class, add

Here you need to add all the data fetched from the database into an array list. Once all the data has been added, you need to sort the data and display the result.

Query query = databaseReference.child("candidates").orderByChild("category").equalTo("President");
query.addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            ArrayList<Candidate> candidates = new ArrayList<>();
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                 int id = dataSnapshot1.child("totalVotes").getValue(Integer.class);
                 String firstName = dataSnapshot1.child("firstName").getValue(String.class);
                 String lastName = dataSnapshot1.child("lastName").getValue(String.class);
                 candidate = new Candidate(firstName, lastName, id);
                 candidates.add(candidate);
             }
             Sorter sorter = new Sorter(candidates);
             ArrayList<Candidate> candidateArrayList = sorter.sortByTotalVotes();
             System.out.println("Max value: " + candidateArrayList.get(0));                            
             System.out.println("Printing the sorted values----------------");
             for (Candidate candidate : candidateArrayList) {    
                  System.out.println(candidate);
             }   
    }

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

    }
});
mayur
  • 374
  • 1
  • 10