访问firebase数据库中的子节点(Android)

时间:2017-03-05 07:19:18

标签: android firebase

这就是我的数据库的外观

mainAlbum
     Album1
        id: ""
        image_name: ""
        image_path: ""
        pic1
           id: ""
           image_name: ""
           image_path: ""
        pic2
           id:  ""
           image_name: ""
           image_path: ""

我能够访问Album1下的image_name和image_path,但我不知道如何访问pic 1和pic 2.有超过1张专辑,我可以全部访问它们,每张专辑都会有很多图片

这是我用来访问数据库的代码。

   private void getData(){
        firebaseDatabaseInstance = FirebaseDatabase.getInstance();

        // get reference to 'users' node
        booksInstance = firebaseDatabaseInstance.getReference("mainAlbum");

        booksInstance.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                setData(dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });

    }

    List<List<String>> booksInfo;
    List<String> temp;
    private void setData(DataSnapshot dataSnapshot){
        booksInfo = new ArrayList<>();
        for (DataSnapshot alert: dataSnapshot.getChildren()) {
            temp = new ArrayList<>();
            Log.d("image_name", (String) alert.child("image_name").getValue());
            Log.d("id", (String) alert.child("id").getValue());
            Log.d("image_path", (String) alert.child("image_path").getValue());
            temp.add((String) alert.child("image_name").getValue());
            temp.add((String) alert.child("id").getValue());
            temp.add((String) alert.child("image_path").getValue());
            booksInfo.add(temp);
        }

        if(booksInfo.size() > 0){
            setGridView();
        }else{
            Toast.makeText(this, "No data Found.", Toast.LENGTH_SHORT).show();
        }
    }

1 个答案:

答案 0 :(得分:0)

通过查看您的firebase数据库结构,只能通过单独访问每张图片来访问相册中的图片。

如果您想以列表形式访问图片,您可能应该使您的结构像

mainAlbum
 Album1
    id: ""
    image_name: ""
    image_path: ""
    pics
        pic1
           id: ""
           image_name: ""
           image_path: ""
        pic2
           id:  ""
           image_name: ""
           image_path: ""

然后你可以通过获取“照片”孩子来访问图片