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.
db1 = FirebaseDatabase.getInstance().getReference().child("Stats").child(currentuser).child("Match").child(team).child("side 1").child("Score");
db1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Integer total = dataSnapshot.getValue(Integer.class);
total_to = total;
I have a variable outside of the OnCreate method at the top of my code like so
int total_to;
I then want to make a chart out of that information, as shown here
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);
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 ;) )
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);
}