如何在不指定父文件夹/ ref的情况下迭代数据快照

Jan*_*nus 1 java android firebase firebase-realtime-database

我想用以下结构迭代数据快照;

 {
"data" : {
"images" : {
  "fw88v6xu6wybamg9zzt6" : {
    "0550e909-3b30-4f83-9725-02fbe45b74ce" : 3,
    "address" : "http://xxxxxxxxxxxxxxx.jpg",
    "author" : "username1",
    "author_id" : "0550e909-3b30-4f83-9725-02fbe45b74ce",
    "location" : "0",
    "rating" : 3
  },
  "osgm6v7kfcjwogo5uv21" : {
    "0550e909-3b30-4f83-9725-02fbe45b74ce" : 4,
    "address" : "xxxxxxxxxxxxxxxx.jpg",
    "author" : "username1",
    "author_id" : "0550e909-3b30-4f83-9725-02fbe45b74ce",
    "location" : "0",
    "rating" : 4
  },
  "prhpcbrrru7z8x6xtolq" : {
    "0550e909-3b30-4f83-9725-02fbe45b74ce" : 6,
    "address" : "xxxxxxxxxxxxxx.jpg",
    "author" : "username2",
    "author_id" : "0550e909-3b30-4f83-9725-02fbe45b74ce",
    "location" : 0,
    "rating" : 6
  }
},
"locations" : {
  "location1" : {
    "author" : "0550e909-3b30-4f83-9725-02fbe45b74ce",
    "latitude" : 11.42222573,
    "longitude" : 58.4348011
  },
  "location2" : {
    "author" : "0550e909-3b30-4f83-9725-02fbe45b74ce",
    "latitude" : 11.42222573,
    "longitude" : 38.4333311
  }
 }
}
Run Code Online (Sandbox Code Playgroud)

具体来说,我正在做的是获取数据/图像子项的快照,因此它将是带有自动生成的引用的三个条目,fw88v6xu6wybamg9zzt6 因此我无法访问特定条目来检索作者的示例,所以我做了我的应用得到

    Iterable<DataSnapshot> imagesDir = snapshot.getChildren();
Run Code Online (Sandbox Code Playgroud)

我不知道如何查看此快照的每个条目并检索输入信息而不知道父参考.(fw88v6xu6wybamg9zzt6)?

好吧,我得到了一个帖子

感谢克里斯,让我找到正确的路径来搜索它,但仍然无法构建正确的语法来达到我想要做的事情.

现在我的方法如下;

  public void onDataChange(DataSnapshot snapshot) {
            for (DataSnapshot child: snapshot.getChildren()) {
                Log.i("MyTag", child.getValue().toString());
                imagesDir.add(String.valueOf(child.getValue()));
            }
            Log.i("MyTag", imagesDir.toString());
Run Code Online (Sandbox Code Playgroud)

从第一个Log我获得每个节点的所有值的字符串,在第二个我构建一个数组以包含所有节点.

我想要做的是添加一个特定的节点(例如地址值)到我在onDataChange方法外面声明的ArrayList ,每次迭代一个孩子.所以在for循环结束时,在这种情况下,我会在arraylist中有三个地址(只有值).

为了做到这一点,构造for循环的正确方法是什么?

好吧,我得到的最终代码给了我正确的结果如下:

              public void onDataChange(DataSnapshot snapshot) {
            for (DataSnapshot child: snapshot.getChildren()) {
                Log.i("MyTag", child.getValue().toString());
                imagesDir.add(child.child("author").getValue(String.class));
            }
            Log.i("MyTag_imagesDirFinal", imagesDir.toString());
Run Code Online (Sandbox Code Playgroud)

Fra*_*len 10

假设你附加ValueEventListenerimages:

public void onDataChange(DataSnapshot imagesSnapshot) {
    for (DataSnapshot imageSnapshot: imagesSnapshot.getChildren()) {
        imagesDir.add(imageSnapshot.child("address").getValue(String.class));
    }
    Log.i("MyTag", imagesDir.toString());
}
Run Code Online (Sandbox Code Playgroud)