You need to enable JavaScript to run this app. Firebase Recycler View无法获取Firebase实时数据库嵌套数据问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Recycler View无法获取Firebase实时数据库嵌套数据问题求助

问题排查与修复方案

核心问题原因

你定义的Model类中Food字段的类型和Firebase实际存储的嵌套结构不匹配,导致Firebase SDK无法正常解析嵌套的Food节点数据。

你当前Model里的Food字段声明是:

HashMap<String,ArrayList<Integer>> Food;

但实际Firebase的Food节点结构是:

  • 第一层key是菜品名(Paneer/Roti/Chicken等)
  • 对应的值是键值对对象(不是数组),key为Full_Plate/Half_Plate,value为对应的数量整数,所以结构是HashMap<String, HashMap<String, Integer>>,不是嵌套ArrayList的结构。

修复步骤

1. 修改Model类的Food字段类型

把Model类中Food相关的声明、构造方法、getter/setter全部替换成正确的类型,修改后的完整Model类如下:

public class Model {
    String Customer,Description,Header;
    // 把原来的ArrayList<Integer>改成HashMap<String, Integer>
    HashMap<String,HashMap<String, Integer>> Food;

    public Model(){

    }

    public Model(String customer, String description, String header, HashMap<String, HashMap<String, Integer>> food) {
        Customer = customer;
        Description = description;
        Header = header;
        Food = food;
    }

    public String getCustomer() {
        return Customer;
    }

    public void setCustomer(String customer) {
        Customer = customer;
    }

    public String getDescription() {
        return Description;
    }

    public void setDescription(String description) {
        Description = description;
    }

    public String getHeader() {
        return Header;
    }

    public void setHeader(String header) {
        Header = header;
    }

    public HashMap<String, HashMap<String, Integer>> getFood() {
        return Food;
    }

    public void setFood(HashMap<String, HashMap<String, Integer>> food) {
        Food = food;
    }
}

2. Adapter中读取Food数据的示例

在Adapter的onBindViewHolder中可以按如下方式遍历Food数据展示:

// 拿到当前item的订单数据
Model currentOrder = getItem(position);
HashMap<String, HashMap<String, Integer>> foodMap = currentOrder.getFood();

// 遍历所有菜品
for (Map.Entry<String, HashMap<String, Integer>> foodEntry : foodMap.entrySet()) {
    String foodName = foodEntry.getKey();
    Integer fullPlateCount = foodEntry.getValue().get("Full_Plate");
    Integer halfPlateCount = foodEntry.getValue().get("Half_Plate");
    // 拼接后展示到对应控件即可
}

3. 可选优化(结构更清晰)

如果不想用两层HashMap嵌套,也可以定义单独的FoodItem类来结构化解析,代码可维护性更高:

public class FoodItem {
    private Integer Full_Plate;
    private Integer Half_Plate;

    public FoodItem() {}

    public Integer getFull_Plate() { return Full_Plate; }
    public void setFull_Plate(Integer full_Plate) { Full_Plate = full_Plate; }
    public Integer getHalf_Plate() { return Half_Plate; }
    public void setHalf_Plate(Integer half_Plate) { Half_Plate = half_Plate; }
}

对应Model类的Food字段改成HashMap<String, FoodItem> Food即可。

修改完成后重新运行项目,嵌套数据即可正常解析展示。


内容的提问来源于stack exchange,提问作者Ankit Goyal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 10:36:07