当我有多个唯一 ID 时从 Firebase 数据库读取数据

Read data from Firebase database when I have multiple unique ids

我在数据库中写入时遇到问题,因为我有多个不知道如何访问的唯一 ID。 我知道为了写作我需要使用这样的东西:

DatabaseReference ref=database.getReference().child("Children")
ChildData data = new ChildData(fullName,age);
ref.push().setValue(data);

我的数据库是这样的:

  {
  "Children" : {
    "55hxObZjRLY9PSZxZxGgSTRKzpc2" : {
      "-MzUih5e40OsWPF_Dj0q" : {
        "age" : "22",
        "fullName" : "Cristina "
      },
      "plays" : {
        "-MznnNih5fItYf2usXB4" : {
          "centiseconds" : "70",
          "currentDate" : "01.04.2022",
          "currentHour" : "04:23:30",
          "numberOfFails" : "5",
          "seconds" : "2"
        }
      }
    }
  },
  "Data" : {
    "id1" : {
      "centiseconds" : "70",
      "currentDate" : "01.04.2022",
      "currentHour" : "04:23:30",
      "numberOfFails" : "5",
      "seconds" : "2"
    }
  }
}

我需要“剧本”child 位于“-MzUih5e40OsWPF_Dj0q”中的“全名”下,而不是单独的 child。如何在不像这样 ref.child("MzUih5e40OsWPF_Dj0q").child("plays").push().setValue(data) 那样硬编码的情况下访问路径?我将在“Children”中有多个具有不同 ID 的 children,我将无法对它们进行硬编码。

有没有函数可以returns唯一id的路径?

这是整个函数:

public void writeNewData
            (String fullName,String age) {
    DatabaseReference reference = database.getReference().child("Data");         
    DatabaseReference ref=myRef.push();
    ChildData data = new ChildData(fullName,age);
    ref.push().setValue(data);
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot ds : snapshot.getChildren()) {
                DatabaseReference playRef=ref.child("plays");
                DatabaseData databaseData = ds.getValue(DatabaseData.class);
                playRef.push().setValue(databaseData);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });
}

编辑: 这是我想要的架构:

{
  "Children" : {
    "55hxObZjRLY9PSZxZxGgSTRKzpc2" : {
      "-MzUih5e40OsWPF_Dj0q" : {
        "age" : "22",
        "fullName" : "Cristina ",
        "plays" : {
          "-MznnNih5fItYf2usXB4" : {
            "centiseconds" : "70",
            "currentDate" : "01.04.2022",
            "currentHour" : "04:23:30",
            "numberOfFails" : "5",
            "seconds" : "2"
          }
        }
      },
    }
  },
  "Data" : {
    "id1" : {
      "centiseconds" : "70",
      "currentDate" : "01.04.2022",
      "currentHour" : "04:23:30",
      "numberOfFails" : "5",
      "seconds" : "2"
    }
  }
}

如果您希望 plays 信息成为 agefullName 属性的同级信息,那么您将需要 plays field/property 在你的 ChildData class.

您需要两个 class,一个代表“戏剧”,一个代表“child”。这些至少看起来像:

public class Play {
  public String centiseconds, currentDate, currentHour, numberOfFails, seconds;
}

public class Child {
  public String age, fullName;
  public Map<String, Play> plays = new HashMap<>();
}

如果您 read/write 这个 class,您将得到 plays 嵌套在 child 的数据下。