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

Android Studio中Firebase实时数据图表不显示,请求技术支持

Firebase实时数据在Android Studio图表中不显示的排查与解决

我需要在Android Studio中以图表形式展示Firebase实时数据,参考ChatGPT及教程编写的代码被判定无问题,但Firebase连接成功后,实时数据库图表却不显示,提示无数据。

【模拟器截图:图表区域提示无数据】

编写的代码

package com.example.wastenotifier;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private BarChart chart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize the chart
        chart = findViewById(R.id.chart);

        // Get reference to your Firebase Database
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("/test/distance");


        // Listen for data changes
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                // Check if the dataSnapshot has any value
                if (dataSnapshot.exists()) {
                    // Get the data from the snapshot
                    Long distance = dataSnapshot.getValue(Long.class);

                    // Prepare the data for the chart
                    List<BarEntry> entries = new ArrayList<>();
                    entries.add(new BarEntry(0, distance != null ? distance : 0));

                    // Create the dataset
                    BarDataSet dataSet = new BarDataSet(entries, "Distance");
                    BarData barData = new BarData(dataSet);

                    // Update the chart with the new data
                    chart.setData(barData);
                    chart.invalidate(); // Refresh the chart
                } else {
                    // Handle the case when there is no data available
                    chart.clear();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                // Handle errors
            }
        });
    }
}

排查与解决建议

  • 确认Firebase路径与数据类型:登录Firebase控制台,检查/test/distance节点是否存在,且存储的是Long类型整数(如100、250)。如果是字符串、浮点数等类型,getValue(Long.class)会返回null,导致图表无有效数据。
  • 检查数据库权限规则:临时将实时数据库规则设置为开放权限(仅测试使用):
    {
      "rules": {
        ".read": true,
        ".write": true
      }
    }
    
    验证是否因权限限制无法获取数据,上线前需修改为安全的权限规则。
  • 添加日志调试:在onDataChange方法中加入日志输出,查看实际获取的数据:
    import android.util.Log;
    // ...
    Log.d("FirebaseDebug", "数据存在:" + dataSnapshot.exists() + ",获取的值:" + dataSnapshot.getValue());
    
    通过Logcat查看日志,判断是数据不存在、类型不匹配还是其他问题。
  • 补充图表基础配置:当前代码仅设置了数据,缺少必要的图表初始化配置,导致可能无法正常显示。在初始化chart后添加:
    chart.setDrawBarShadow(false);
    chart.setDrawValueAboveBar(true);
    chart.getDescription().setEnabled(false);
    chart.setPinchZoom(false);
    chart.setDrawGridBackground(false);
    chart.getAxisLeft().setAxisMinimum(0f); // 设置Y轴最小值,避免数据为0时不显示
    
  • 适配数据类型:如果Firebase中存储的是浮点数(如123.5),将获取数据的代码改为:
    Double distance = dataSnapshot.getValue(Double.class);
    entries.add(new BarEntry(0, distance != null ? distance.floatValue() : 0f));
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 23:14:55