实时数据库图表没有出现,它说图表中没有数据,而与 firebase 的连接已成功完成

问题描述 投票:0回答:1

我想要 Android Studio 中以图表形式表示的 Firebase 实时数据。任何人都可以帮助我实现这个目标吗?我已经问过 chatgpt 和其他教程,但根据他们的说法,有问题的代码是正确的。下面是我写的代码。

模拟器

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
            }
        });
    }
}

java android firebase mobile charts
1个回答
0
投票

确保在 Firebase 控制台中,实时数据库已将这些规则设置为 true。以及以下设置。

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.github.mikephil.charting.charts.BarChart
        android:id="@+id/chart"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

主要活动:

public class MainActivity extends AppCompatActivity {

    private BarChart chart;

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

        chart = findViewById(R.id.chart);

        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("/test/distance");

        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
               
                if (dataSnapshot.exists()) {
                    
                    Long distance = dataSnapshot.getValue(Long.class);

                    List<BarEntry> entries = new ArrayList<>();
                    entries.add(new BarEntry(0, distance != null ? distance : 0));

                    BarDataSet dataSet = new BarDataSet(entries, "Distance");
                    dataSet.setColor(getResources().getColor(R.color.colorPrimary)); // Set color if needed
                    dataSet.setValueTextColor(getResources().getColor(R.color.colorAccent));

                    BarData barData = new BarData(dataSet);
                    barData.setBarWidth(0.9f); // Set bar width

                    chart.setData(barData);
                    chart.setFitBars(true); // Make the x-axis fit exactly all bars
                    chart.invalidate(); // Refresh the chart
                } else {
                    chart.clear();
                    chart.invalidate(); // Refresh the chart
                }
            }

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

必要的权限:

<uses-permission android:name="android.permission.INTERNET" />

build.gradle 中 Firebase 和 MPAndroidChart 的必要依赖项

dependencies {
    implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
    implementation 'com.google.firebase:firebase-database:20.0.5'
}
© www.soinside.com 2019 - 2024. All rights reserved.