如何多次获取子节点并保存父节点

时间:2018-12-19 11:59:03

标签: java android firebase firebase-realtime-database

假设我的数据库具有以下结构:

data
 |___randomId1
 |       |_________randomData1
 |                       |______Key1: value
 |                       |______Key2: value
 |___randomId2
         |_________randomData2
                         |______Key1: value
                         |______Key2: value

我想迭代获取所有值,并保存父ID(randomId1,randomId2)。我该如何循环?现在我有以下内容:

ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
               // what to put here to get the values and also save the ids?
        }
    }

您会看到每个randomData具有相同的映射(键1和键2)。

1 个答案:

答案 0 :(得分:2)

要解决此问题,您需要使用两个嵌套循环,如以下代码行所示:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dataRef = rootRef.child("data");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
            String parentKey = dSnapshot.getKey();

            for(DataSnapshot ds : dSnapshot.getChildren()) {
                String key = ds.getKey();

                String key1 = ds.child("Key1").getValue(String.class);
                String key2 = ds.child("Key2").getValue(String.class);
                Log.d(TAG, key1 + " / " + key2);
            }
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
dataRef.addListenerForSingleValueEvent(valueEventListener);