You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Firebase开发中snapshot.getChildren()有值但getValue()返回null

问题根因

你的代码逻辑存在两层问题:

  1. 内层循环遍历的是单个食谱节点的所有直接子节点,当循环变量ds本身就是ingredients节点时,你调用ds.child("ingredients")相当于查找ingredients/ingredients这个不存在的路径,自然返回null。
  2. 外层已经拿到了所有食谱的完整快照,不需要再针对单个食谱重复发起数据库请求,属于多余操作。

修复方案

简化版(去掉多余请求,效率更高)

rootReference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        for (DataSnapshot recipeSnapshot : snapshot.getChildren()) {
            String recId = recipeSnapshot.getKey();
            Log.d(TAG, "RECID: " + recId);
            // 直接从当前食谱快照取ingredients节点,无需重复请求
            DataSnapshot ingredientsSnapshot = recipeSnapshot.child("ingredients");
            if (ingredientsSnapshot.exists()) {
                ArrayList<String> ingList = new ArrayList<>();
                for (DataSnapshot ingSnapshot : ingredientsSnapshot.getChildren()) {
                    String ingName = ingSnapshot.getValue(String.class);
                    ingList.add(ingName);
                    Log.d(TAG, "食材: " + ingName);
                }
                // 此处可添加食材列表对比逻辑
            }
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        Log.e(TAG, "读取失败: " + error.getMessage());
    }
});

若保留原有嵌套请求写法,直接修改内层逻辑即可

@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
    // 无需遍历子节点,直接从当前食谱快照取ingredients节点
    DataSnapshot ingredientsSnapshot = snapshot.child("ingredients");
    Log.d(TAG, "SPECIFIC: " + ingredientsSnapshot);
    if(ingredientsSnapshot.getValue() != null) {
        Log.d(TAG, "INGREDIENTS NOT NULL");
        ArrayList<String> ing = new ArrayList<String>();
        for (DataSnapshot ings : ingredientsSnapshot.getChildren()) {
            ing.add(ings.getValue(String.class));
            Log.d(TAG, "INGS: " + ings);
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:15:03