简体   繁体   English

Firebase数据库,如何使用数据库节点的内容填充Spinner?

[英]Firebase Database, how to fill a Spinner with the contents of a databse node?

I'm trying to fill a spinner with the contents of a node. 我试图用节点的内容填充微调器。 The node is called Members and is structured like this: 该节点称为成员,其结构如下:

Members:
-LC7n2qjCocAME4XiGuH: "ZFjiRpFJ7HgxNWBQYOhNwS6HUys2"
-LC7nSFctVUdGr6pp7k-: "XIiVCBeu5TaxMCZY7ZIsINtKKBB2"

I am trying to populate the Spinner with the data assigned to the keys. 我正在尝试使用分配给按键的数据填充微调框。 So in this case the spinner would have two entries "ZFjiRp..." and "XIiVC...". 因此,在这种情况下,微调器将具有两个条目“ ZFjiRp ...”和“ XIiVC ...”。 The Members node will have data added and deleted while the application runs and the spinner needs to reflect that. 在应用程序运行时,“成员”节点将添加和删除数据,微调器需要反映这些数据。 I figured a for loop to get the number of children of the members node to fill the spinner would work, but I don't know how to go through the node and read the data one by one. 我想出了一个for循环来获取填充该微调器的成员节点的子节点数目,但我不知道如何遍历该节点并逐个读取数据。

Thanks in advance. 提前致谢。

  1. Get a database reference of your firebase db. 获取您的Firebase数据库的数据库参考。
  2. Attach a childeventlistener on that ref. 在该参考文献上附加一个childeventlistener
  3. In OnChildAdded and OnChildChanged callback get the value from datasnapshot object and bind to your spinner. OnChildAddedOnChildChanged回调中,从datasnapshot对象获取值并绑定到微调器。

You can do it like this: 您可以这样做:

final ArrayList<String> arrayList = new ArrayList<>();
        firebaseReference.child("Members").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot != null) {
                    Iterator<DataSnapshot> iterable = dataSnapshot.getChildren().iterator();
                    for (Iterator<DataSnapshot> it = iterable; it.hasNext(); ) {
                        DataSnapshot dataSnapshot1 = it.next();
                        arrayList.add(dataSnapshot1.getValue(String.class));
                    }
                    //set arraylist here to spinner adapter
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

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

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