如何从Firebase检索嵌套数据

时间:2020-07-03 21:09:32

标签: android firebase firebase-realtime-database

这是我的firebase数据的结构:

Structure of data in firebase

我在检索所有“ menukedai”数据时遇到问题。通过使用下面的代码,“ menukedai”的数据没有出来。供您参考,“ menukedai”的数据将来自用户。

这是我的尝试

foodDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads").child("menukedai");

foodDatabaseRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            foodmenu foodmenu = postSnapshot.getValue(foodmenu.class);
            fooddata.add(foodmenu);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Toast.makeText(foodlist.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

这是我的美食菜单。

package com.example.trialfoodbuddy;

public class foodmenu {
    private String Foodimage;
    private String Foodname;
    private CharSequence Foodprice;

    public foodmenu(){
        //empty constructor needed
    }
    public foodmenu(String foodimage, String foodname, CharSequence foodprice){
        Foodimage = foodimage;
        Foodname = foodname;
        Foodprice = foodprice;
    }

    public String getFoodimage(){
        return Foodimage;
    }

    public String getFoodname(){
        return Foodname;
    }

    public CharSequence getFoodprice(){
        return Foodprice;
    }

    public void setFoodimage(String foodimage){
        Foodimage = foodimage;
    }

    public void setFoodname(String foodname){
        Foodname = foodname;
    }

    public void setFoodprice(CharSequence foodprice){
        Foodprice = foodprice;
    }
}

1 个答案:

答案 0 :(得分:0)

我相信您希望将信息嵌套在“ menukedai”下,因此您需要为该信息添加另一个循环

foodDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
foodDatabaseRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot uploadSnapshot : dataSnapshot.getChildren()) {
            // this is where you actually getting the information 
            for(DataSnapshot menuItemSnapshot : uploadSnapshot.child("menukedai").getChildren()){
                foodmenu foodmenu = menuItemSnapshot.getValue(foodmenu.class);
                fooddata.add(foodmenu);
            }
        }
    }
    // Log the values and check them to make sure you getting the data you want if always nice so I added it for you here
    Log.i("Values","My values are:"+foodmenu);
    @Override
    public void onCancelled(DatabaseError databaseError) {
        Toast.makeText(foodlist.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

通常来说,您应该始终在数据库中的类中使用变量名,以便在获取信息时,构造函数将知道将什么值分配给类中的哪个变量。