2

I've been stuck on this problem for a while now and I can't seem to solve it. I'm trying to store a value from my database by using "getValue" in a global variable. I want to use this variable to make a piechart (Anychart) out of.

Here is the code I'm using to pull the data.

I have a variable outside of the OnCreate method at the top of my code like so

int total_to;

The problem is that the code doesn't seem to store the datasnapshot value in the global variable, so the total_to value is always zero. Any help would be appreciate. Note I'm new to java (go easy on me ;) )

hanzn98
  • 35
  • 1
  • 6
  • As Peter answered: any code that requires the data from the database will need be **inside** `onDataChange` or be called from there. See https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Feb 27 '20 at 14:16

1 Answers1

3

The onDataChange is asynchronous which means the code after onDataChange will be executed before the data is fully retrieved. Therefore total_to outside of onDataChange will be zero. You need to do the following to fix this problem:

 if (dataSnapshot.exists()) {
       Integer total = dataSnapshot.getValue(Integer.class);
       total_to = total;

       Pie pie = AnyChart.pie();
       List<DataEntry> data = new ArrayList<>();
       data.add(new ValueDataEntry("y", total_to) );
       data.add(new ValueDataEntry("x", 7) );
       pie.data(data);
       AnyChartView anyChartView = (AnyChartView)findViewById(R.id.piechart);
       anyChartView.setChart(pie);
}
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • Thank you! this helped a lot. – hanzn98 Feb 27 '20 at 14:23
  • How can I solve it with the pie outside the on data change snapshot?. My code has many database references and the chart is made up from the total of multiple entries. The total_to will increase as it goes through each db ref. – hanzn98 Feb 27 '20 at 15:59