How do I store a firebase value as an global integer in my java class

Viewed 66

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

1 Answers

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