简体   繁体   English

Firebase 子节点检索

[英]Firebase child node retrieving

我的火力基地

I'm trying to retrieve all child nodes "userID" from firebase and store them in userList array list.我正在尝试从 firebase 中检索所有子节点“userID”并将它们存储在userList数组列表中。 Datasnapshot object dsp pulls all the data but it can't pass it to userList which always empty. Datasnapshot object dsp提取所有数据,但无法将其传递给始终为空的 userList。 Here is my code snippet:这是我的代码片段:

groupList = FirebaseDatabase.getInstance ().getReference ().child ( "Group Members" );

groupList.addValueEventListener(new ValueEventListener()
{

    @Override
    public void onDataChange( DataSnapshot dataSnapshot)
    {
        List<String> userList = new ArrayList<> ();

        for (DataSnapshot dsp : dataSnapshot.getChildren ())
        {

            String  uID = dsp.child ("userID").getValue().toString ();
            userList.add ( uID );
        }
    }

What do you suggest to change in the code?您建议在代码中进行哪些更改?

You're only looping over the direct child nodes of Group Members , so your dsp variable points to Android11 , mgrp and the lovers .您只循环Group Members的直接子节点,因此您的dsp变量指向Android11mgrpthe lovers Since none of those has a property userID , the uID variable will indeed always be null or empty.由于这些都没有属性userID ,因此uID变量确实总是 null 或空。

You'll need to loop over the nested level in your JSON (the keys like MtNY... ) to be able to get the userID values.您需要遍历 JSON 中的嵌套级别(像MtNY...这样的键)才能获取userID值。

So:所以:

groupList = FirebaseDatabase.getInstance().getReference("Group Members" );

groupList.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange( DataSnapshot dataSnapshot) {
        List<String> userList = new ArrayList<> ();

        for (DataSnapshot snapshot: dataSnapshot.getChildren ()) {
            for (DataSnapshot userSnapshot: snapshot.getChildren ()) {
                String  uID = userSnapshot.child ("userID").getValue(String.class);
                userList.add ( uID );
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM