Firebase 检索最高 100 分 [英] Firebase retrieve highest 100 score

查看:16
本文介绍了Firebase 检索最高 100 分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 firebase 的屏幕截图:我正在尝试检索 firebase 数据库中的最高 100 分我正在使用此代码向 firebase 添加新节点:

This is a screen shot of my firebase: I am trying to retrieve the highest 100 score in firebase database I am using this code to add new node to firebase:

 Map<String, String> post1 = new HashMap<String, String>();
        post1.put("name",name);
        post1.put("score",score);
        myRef.push().setValue(post1);

这是我用来检索最高 100 分但不起作用的代码(该代码有效,但不能检索最高 100 分)

And this is the code I am using to retrieve the highest 100 score which doesn't work (the code works but it is not retrieving the highest 100 score)

 Query queryRef = myRef.orderByChild("score").limitToFirst(100);
        queryRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                    Score score=postSnapshot.getValue(Score.class);
                    Log.d("test"," values is " + score.getName()  + " " + score.getScore());
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        }); 

推荐答案

Firebase 查询始终按升序排列.因此,您需要获取最后 100 个,而不是前 100 个.

Firebase queries are always in ascending order. So you'll need to get the last 100, instead of the first 100.

Query queryRef = myRef.orderByChild("score").limitToLast(100);

然后在客户端,您需要反转项目.

Then client-side you'll need to reverse the items.

或者,您可以为您的项目添加倒置属性invertedScore: -99.如果这样做,您可以按倒排的分数排序,而不必反转数组.

Alternatively you can add a inverted property to your items invertedScore: -99. If you do that, you can order by that inverted score and won't have to reverse the array.

这个场景以前经常被提及.我强烈建议您研究其中的一些:

This scenario has been covered frequently before. I highly recommend you study some of these:

  • data sorting in firebase
  • Firebase Leaderboard, best Implmentation. SQL Joins and orderby (as recently as yesterday)
  • Display posts in descending posted order
  • Firebase Data Desc Sorting in Android
  • Swift - How to create Sort query as Descending on Firebase?

这篇关于Firebase 检索最高 100 分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆