Ngugi Kariuki
Ngugi Kariuki

Reputation: 184

Filter snapshot results in firebase

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

Upvotes: 0

Views: 502

Answers (1)

mayur
mayur

Reputation: 384

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) {

    }
});

Upvotes: 1

Related Questions