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

Firebase实时数据库Snapshot不存在,无法读取题目数据的解决方法

问题描述

尝试从Firebase实时数据库读取题目数据,但代码始终执行else分支,无法进入if分支(因为Snapshot不存在)。

日志输出

2024-10-06 17:39:26.060 23619-23619 ıd check com.example.quiztime D -O8IX4259O4p5Ko_uh4e-O8GtSPIwhXwbPfYy0Bc

实时数据库结构

{  
  "categories": {    
    "-O8GtSPIwhXwbPfYy0Bc": {      
      "categoryImage": "https://firebasestorage.googleapis.com/v0/b/quiztimeadminapp.appspot.com/o/categoryImage%2F1727950867993?alt=media&token=312244da-1e8e-4188-8f81-b7b81d056125",      
      "categoryName": "almanca ",      
      "subCategories": {        
        "-O8HS_G7EjfqXDUij4El": {          
          "categoryName": "a1 almanca",          
          "questions": {            
            "-O8LtLHmg-9rgchOJiKT": {              
              "correctAnswer": "Bukres ",              
              "optionA": "Londra ",              
              "optionB": "Bukres ",              
              "optionC": "Paris ",              
              "optionD": "Madrid",              
              "question": "ingilterenin baskenti neresidir "            
            },            
            "-O8WplOEJ9gMN_tW0DjM": {              
              "correctAnswer": "Sjsj",              
              "optionA": "Sjsj",              
              "optionB": "Sjsj",              
              "optionC": "Sjjs",              
              "optionD": "Sjdj",              
              "question": "deneme 2"            
            }          
          }        
        },        
        "-O8IX4259O4p5Ko_uh4e": {          
          "categoryName": "a2 almanca"        
        }      
      }    
    }  
  }
}

代码实现

Log.d("ıd check",subCatId+catId);
database.getReference().child("categories").child(catId)
.child("subCategories").child(subCatId)
.child("questions").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        if (snapshot.exists()) {
            Log.d("exixtance","DOES EXİSTS");
            timer.start();
            for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                prossesdata(dataSnapshot);
                loadingdialog.dismiss();
            }
            if (list.size() > 0) {
                for (int i = 0; i < 4; i++) {
                    binding.optioncontainer.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkAnswer((Button) v);
                        }
                    });
                }
                playAnimation(binding.question, 0, list.get(position).getQuestion());

                binding.buttonnext.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        enableOptions(true);
                        position++;
                        if (position == list.size()) {
                            timer.cancel();
                            Intent intent = new Intent(QuestionActivity.this, ScoreActivity.class);
                            long totaltime = questionTime * 60 * 100;
                            intent.putExtra("timetaken", totaltime - timeLeft);
                            intent.putExtra("correct", correctAnswer);
                            intent.putExtra("wrong", wrongAnswer);
                            intent.putExtra("totalquestion", list.size());
                            startActivity(intent);
                            finish();
                            return;
                        }
                        count = 0;
                        playAnimation(binding.question, 0, list.get(position).getQuestion());
                    }
                });

                binding.buttonsubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(QuestionActivity.this, ScoreActivity.class);
                        long totaltime = questionTime * 60 * 100;
                        intent.putExtra("timetaken", totaltime - timeLeft);
                        intent.putExtra("correct", correctAnswer);
                        intent.putExtra("wrong", wrongAnswer);
                        intent.putExtra("totalquestion", list.size());
                        startActivity(intent);
                    }
                });
            }
        } else {
            Toast.makeText(QuestionActivity.this, ""+list.size(), Toast.LENGTH_SHORT).show();
            loadingdialog.dismiss();
        }
    }
});
问题原因与修复方案

问题根源

从日志和数据库结构可直接定位问题:

  • 日志输出的subCatId为-O8IX4259O4p5Ko_uh4e,catId为-O8GtSPIwhXwbPfYy0Bc
  • 数据库中该subCatId对应的子分类下不存在questions节点,因此Firebase返回的Snapshot为空,代码自然进入else分支。

修复步骤

  1. 确认目标子分类正确性

    • 如果需要读取有题目的子分类,检查subCatId是否传错,应使用包含questions的-O8HS_G7EjfqXDUij4El而非当前的-O8IX4259O4p5Ko_uh4e。
    • 如果确实要访问-O8IX4259O4p5Ko_uh4e,需先在Firebase控制台给该节点添加questions数据。
  2. 增加路径日志排查
    在onDataChange方法开头添加日志,验证当前访问的数据库路径是否正确:

    String dbPath = database.getReference().child("categories").child(catId)
        .child("subCategories").child(subCatId).child("questions").toString();
    Log.d("db_path", "当前访问路径:" + dbPath);
    

    对比路径与数据库结构,快速确认节点是否存在。

  3. 优化无数据提示
    将else分支的Toast提示改为用户易懂的内容:

    Toast.makeText(QuestionActivity.this, "当前分类暂无题目", Toast.LENGTH_SHORT).show();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 13:37:06