在Firebase中筛选快照结果

huangapple go评论87阅读模式
英文:

Filter snapshot results in firebase

问题

以下是翻译好的内容:

这是我的数据库:

在Firebase中筛选快照结果

对于每个类别,它应该返回具有最高“totalVotes”的候选人。

这是我的代码:

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

它会返回具有最高票数的候选人,而不是最近的候选人。如何在数据快照中过滤结果,以显示具有最高“totalVotes”的候选人。

谢谢

英文:

Here is my database:

在Firebase中筛选快照结果

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

<!-- end snippet -->

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

答案1

得分: 1

我复现了你的问题,并找到了一种获取得票最多候选人的方法。

在你的模型类中添加以下方法。

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

要覆盖compareTo方法,你需要通过implements Comparable<Candidate>来实现Comparable接口。

创建一个用于排序的类

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;
    }
}

在你的Activity类中添加

在这里,你需要将从数据库中获取的所有数据添加到一个数组列表中。一旦所有数据都添加完毕,你需要对数据进行排序并显示结果。

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 candidate = new Candidate(firstName, lastName, id);
            candidates.add(candidate);
        }
        Sorter sorter = new Sorter(candidates);
        ArrayList<Candidate> candidateArrayList = sorter.sortByTotalVotes();
        System.out.println("最大值: " + candidateArrayList.get(0));                            
        System.out.println("打印排序后的值----------------");
        for (Candidate candidate : candidateArrayList) {    
            System.out.println(candidate);
        }   
    }
    
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
    
    }
});
英文:

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() &gt; o.getTotalVotes() ? -1 :
                (this.getTotalVotes() == o.getTotalVotes() ? 0 : 1));
    }

To override the compareTo method, you need to implement Comparable class by implements Comparable&lt;Candidate&gt;

Create a class to sort the values

public class Sorter {

    ArrayList&lt;Candidate&gt; candidateList = new ArrayList&lt;&gt;();
    public Sorter(ArrayList&lt;Candidate&gt; candidateList) {
        this.candidateList = candidateList;
    }
    public ArrayList&lt;Candidate&gt; 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(&quot;candidates&quot;).orderByChild(&quot;category&quot;).equalTo(&quot;President&quot;);
query.addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            ArrayList&lt;Candidate&gt; candidates = new ArrayList&lt;&gt;();
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                 int id = dataSnapshot1.child(&quot;totalVotes&quot;).getValue(Integer.class);
                 String firstName = dataSnapshot1.child(&quot;firstName&quot;).getValue(String.class);
                 String lastName = dataSnapshot1.child(&quot;lastName&quot;).getValue(String.class);
                 candidate = new Candidate(firstName, lastName, id);
                 candidates.add(candidate);
             }
             Sorter sorter = new Sorter(candidates);
             ArrayList&lt;Candidate&gt; candidateArrayList = sorter.sortByTotalVotes();
             System.out.println(&quot;Max value: &quot; + candidateArrayList.get(0));                            
             System.out.println(&quot;Printing the sorted values----------------&quot;);
             for (Candidate candidate : candidateArrayList) {    
                  System.out.println(candidate);
             }   
    }
    
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
    
    }
});

huangapple
  • 本文由 发表于 2020年4月9日 09:30:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/61112573.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定