0

I can't transfer the data of the database and make it as input for the bar graph. Can anyone know this?

here's the graph

I don't know the problem is it just won't work. Take note that there's no error while the application is running so really don't know how to fix it. Please help me.


import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.example.greenerthumb.databinding.ActivityTrackingHistoryBinding;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.android.material.navigation.NavigationView;
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 org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

public class TrackingHistory extends AppCompatActivity {
    ActivityTrackingHistoryBinding binding;
    DrawerLayout drawerLayout;
    NavigationView navigationView;
    ActionBarDrawerToggle drawerToggle;
    private TextView greetingsTxt;

    FirebaseDatabase firebaseDatabase;
    DatabaseReference databaseReference;


    private List<String> monthValues = Arrays.asList("January","February","March","April", "May", "June", "July", "August","September","October","November","December");

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (drawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityTrackingHistoryBinding.inflate(getLayoutInflater());
        setContentView(R.layout.activity_tracking_history);

        greetingsTxt = findViewById(R.id.greetings);
        showGreetings();


        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReference = firebaseDatabase.getReference("Monthly History").child("January");
        float rawData = monthJanuary;
        getJanData();




        BarChart barChart = findViewById(R.id.historyMonth);
        barChart.getAxisRight().setDrawLabels(false);

        ArrayList<BarEntry> entries1 = new ArrayList<>();
        entries1.add(new BarEntry(0, rawData));



        YAxis yAxis = barChart.getAxisLeft();
        yAxis.setAxisMaximum(0f);
        yAxis.setAxisMaximum(500f);
        yAxis.setAxisLineWidth(2f);
        yAxis.setAxisLineColor(Color.BLACK);
        yAxis.setLabelCount(10);

        BarDataSet dataSet = new BarDataSet(entries1, "MONTH");
        dataSet.setColors(ColorTemplate.MATERIAL_COLORS);

        BarData barData = new BarData(dataSet);
        barChart.setData(barData);

        barChart.getDescription().setEnabled(false);
        barChart.invalidate();

        barChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(monthValues));
        barChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        barChart.getXAxis().setGranularity(1f);
        barChart.getXAxis().setGranularityEnabled(true);
        barChart.animateY(5000);
        barChart.animateX(5000);


       
        

    private void getJanData() {
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                Float value = snapshot.getValue(Float.class);
                monthJanuary = value;
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(TrackingHistory.this,"Failed to get data.",Toast.LENGTH_SHORT).show();
            }
        });
    }

   

I already tried several methods, but the graph is still empty.

Greedy Ban
  • 11
  • 1
  • You data is empty as obviosuly `FirebaseDatabase` works asynchrounous ... your `getJanData` doesn't does what it promise... it just starts process of getting data ... and data are ready to use in `onDataChange` not right after `getJanData` ends ... even if ... you do nothing with `monthJanuary` after this call so ... your code is FUBAR – Selvin Jul 31 '23 at 09:54
  • I'm not sure I understand. What exactly in this code doesn't work the way you expect? Tell us what is wrong with shared code. Do you have any errors? – Alex Mamo Jul 31 '23 at 09:56
  • As Selvin commented: data is loaded from Firebase (and most modern cloud APIs) asynchronously. In your case, your code that builds the chart runs before the `onDataChange` ever executes. I recommend setting breakpoints and running in the debugger, or adding some logging to verify this - as it's a very common source of confusion. --- To solve the problem, any code that needs data from the database will have to be inside `onDataChange`, be called from there, or be otherwise synchronized. – Frank van Puffelen Jul 31 '23 at 14:14

0 Answers0