Android Firebase过滤数据

时间:2016-09-26 17:23:31

标签: android firebase firebase-realtime-database

我在firebase上使用以下格式的JSON:

"products" : {
    "-KS9-I-mz7k_4IqYMQdX" : {
      "brand" : "champion",
      "name" : "x2 style",
      "users" : {
        "oGNKfltdMsVAfjDN63QjjITGnhw1" : {
          "-KSIpwMZxesepEdNN1CW" : {
            "-KS9IQkdC0-lRYp0hzAN" : true
          }
        }
      }
    },
    "-KS9-IkweDZlNf_qbbrX" : {
      "brand" : "champion",
      "name" : "wtab 709 tab",
      "users" : {
        "NKfltdMsVAfjDN63QjjITGnjdjjj" : {
         "-KSIpwMZxesepEdNN1CW" : {
            "-KS9IQkdC0-lRYp0hzAN" : true
          }
        }
      }
    }
}

我需要获得拥有此密钥oGNKfltdMsVAfjDN63QjjITGnhw1的所有用户。我试过过滤关键,价值和孩子。但是没有用。

1 个答案:

答案 0 :(得分:0)

有关迭代数据快照的示例,请参阅文档:

myTopPostsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
            // TODO: handle the post
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Getting Post failed, log a message
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
        // ...
    }
});

以下是此示例,但这一次,我尝试使用您的代码更好地为您解释解决方案:

mDatabase.child("products").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshotLevel1) {
        for(DataSnapshot dataSnapshotLevel2: dataSnapshotLevel1.getChildren()){
            for(DataSnapshot dataSnapshotLevel3: dataSnapshotLevel2.getChildren()){
                if(child.getKey().equals("users")){
                    for(DataSnapshot deeperData: data.getChildren()){
                        if(child.getKey().equals("oGNKfltdMsVAfjDN63QjjITGnhw1")){
                            //Here is where you do whatever you need to do now that you found your child.
                        }
                    }
                }
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.w(TAG, "getUser:onCancelled", databaseError.toException());
        // ...
    }
});