Firebase数据库按未知节点的时间排序

时间:2018-03-27 20:46:17

标签: android firebase firebase-realtime-database

我正在尝试按时间顺序检索以下内容:

Firebase Database Structure

已知值是经过身份验证的用户的当前令牌,但未知值是之前从服务器环境创建的用户。

    mDatabase = FirebaseDatabase.getInstance().getReference("users");

    mDatabase.child("users").child(user.getUid());

    mDatabase.child(user.getUid()).addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {


            GenericTypeIndicator<Map<String, Object>> t = new GenericTypeIndicator<Map<String, Object>>() {
            };
            Map<String, Object> map = dataSnapshot.getValue(t);

            assert map != null;


            for (Object e : map.values()) {
                list.add(e.toString());
            }

            for (Object e : map.keySet()) {
                list1.add(e.toString());
            }

我曾尝试在addValueEventListener上使用orderByChild(&#34; time&#34;),但我认为它不起作用,因为我无法指向数据库中的正确位置,因为我无法获取用户

修改

            try {
                for (int i = list1.size()-1; i == list1.size()-1; i++) {

                    String guestname = String.valueOf(dataSnapshot.child(list1.get(i)).child("username").getValue());
                    String guestemail = String.valueOf(dataSnapshot.child(list1.get(i)).child("email").getValue());
                    String guestpassword = String.valueOf(dataSnapshot.child(list1.get(i)).child("password").getValue());

                    Log.w(TAG, "Name of newest value is " + guestname);
                    Log.w(TAG, "Email of newest value is " + guestemail);
                    Log.w(TAG, "Password of newest value is " + guestpassword);
                    guestname1 = guestname;
                    guestpassword1 = guestpassword;
                    guestemail1 = guestemail;
                }

1 个答案:

答案 0 :(得分:0)

您想要使用orderByChild()

mDatabase = FirebaseDatabase.getInstance().getReference("users");

Query query = mDatabase.child(user.getUid()).orderByChild("time")

query.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (dataSnapshot childNode: dataSnapshot.getChildren()) {
      System.out.printl(childNode.getKey()); //this is the unknown key you marked
      System.out.printl(childNode.child("time").getValue(Long.class));
    }
  }

  ...