【问题标题】:Retrieving child from firebase with no tag从没有标签的firebase中检索孩子
【发布时间】:2019-01-29 10:59:07
【问题描述】:

我正在尝试从没有标签/名称的 firebase 中检索子节点。我知道这不是在 firebase 中存储子节点的正确方法,它只是我可以存储它们以使计数函数工作的唯一方法。

我正在尝试检索“技术”或“生物学和生态学”等类别。我的数据库设置如下:

  CountLikes{
    Project 23{
      Biological and Ecological{
          Votes: 1
                }}

    Project 32{  
      Biological and Ecological{ 
           Votes: 0
              }}

     Project 439{
      Technology{ 
          Votes: 2
               }}

我可以使用以下方法检索项目名称(即“Project 23”、“Project 32”)和投票数:

 //Button Click Listener
    mReadButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("CountLikes/");

            ValueEventListener eventListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {



                    for(DataSnapshot ds : dataSnapshot.getChildren()) {
                       String name = ds.getKey();
                       Long vote = ds.child("Votes").getValue(Long.class);


                       mProjectName.setText(name);
                       mProjectCategory.setText(String.valueOf(vote));
                    }
               }

                @Override
                public void onCancelled(DatabaseError databaseError) {}
            };
           ref.addListenerForSingleValueEvent(eventListener);

无论如何我可以检索类别吗?

【问题讨论】:

  • 如果vote 显示正确的结果,那么name 应该是高于它的级别(Biological and EcologicalTechnology)。如果不是这样,您能否显示数据库中的实际 JSON(作为文本,请不要截图)?您可以通过单击Firebase Database console 上溢出菜单 (⠇) 中的“导出 JSON”链接来获取此信息。
  • 对不起,你是对的!我想我需要帮助检索的是“Project 23”、“Project 32”而不是名称!

标签: java android firebase firebase-realtime-database


【解决方案1】:

我不清楚您的数据结构的含义,因此很难准确理解您要查找的内容。但是这段代码会用你当前拥有的监听器遍历整个DataSnapshot

DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("CountLikes");

ref.addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for(DataSnapshot child: dataSnapshot.getChildren()) {
      System.out.println(child.getKey()); // prints "Project 23", "Project 32", etc
      for(DataSnapshot grandchild: child.getChildren()) {
        System.out.println(grandchild.getKey()); // prints "Biological and Ecological", etc
        System.out.println(grandchild.child("Votes").getValue(Long.class)); // prints 1, 0, etc
      }

    }

 }

  @Override
  public void onCancelled(DatabaseError databaseError) {
    throw databaseError.toException();
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-11
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    相关资源
    最近更新 更多