具有最大价值的Firebase返回子项 [英] Firebase return child that have biggest value

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

问题描述

我正在使用firebase一段时间,但是我遇到了一个问题,我想让孩子得到最大的价值:

I am using firebase for a little while but I have stuck at one problem that I want to get the child that have the biggest value:

示例如下是我的json(手动编辑):

Example here's my json (edited manually):

{
  "Players" : {
    "Scores" : {
      "-JFUIwudw93dkD" : {
        "rank" : 0
      },
      "-KSFOW833nSfkod" : {
        "rank" : 8
      },
      "-Kk5WfuJ8mlZTPdeUC40" : {
        "rank" : 2
      },
      "-SKKQuyhso83ds" : {
        "rank" : 14
      }
    }
  },

我需要获得最高等级的子钥匙. 因此,我需要一个"-SKKQuyhso83ds"子代.

I need to get the child key for the highest rank. So I need the "-SKKQuyhso83ds" child.

我已经使用了这种方法,但是不起作用:

I have use this method but It doesn't work:

final DatabaseReference mDatabasePlayers = FirebaseDatabase.getInstance().getReference().child("Players");
    Query mDatabaseHighestPlayer = mDatabasePlayers.child("Scores").orderByChild("rank").limitToFirst(1);
    mDatabaseHighestPlayer.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot){
            //This returns null
            String Key = dataSnapshot.getKey();
            Toast.makeText(main.this,Key,Toast.LENGTH_LONG).show();}
        @Override
        public void onCancelled(DatabaseError databaseError) {}});

但是那不起作用,所以我正在等待一些帮助兄弟.

but that doesn't work so I'am waiting for some help brothers.

推荐答案

Firebase查询按升序排序.由于您按排名排序并限制在第一位,因此您将获得最低得分.要获得最高分数,请使用limitToLast(1).

Firebase queries are ordered ascending. Since you order by rank and limit to the first result, you'll get the lowest score. To get the highest score, use limitToLast(1).

此外,当您对Firebase数据库执行查询时,可能会有多个结果.因此,快照包含这些结果的列表.即使只有一个结果,快照也会包含一个结果的列表.

In addition, when you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

所以总共:

DatabaseReference mDatabasePlayers = FirebaseDatabase.getInstance().getReference().child("Players");
Query mDatabaseHighestPlayer = mDatabasePlayers.child("Scores").orderByChild("rank").limitToLast(1);
mDatabaseHighestPlayer.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot){
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            String Key = childSnapshot.getKey();
            Toast.makeText(main.this,Key,Toast.LENGTH_LONG).show();
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException(); // don't swallow errors
    }
});

这篇关于具有最大价值的Firebase返回子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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