Reputation: 303
I want to get data from firebase realtime database.
I need to get the isPresent and otDuration value inside all the date's. My database reference is
mDatabase = FirebaseDatabase.getInstance().getReference().child("employee").child(emp_ID).child("attendance");
I need to access otDuration
so that I can calculate the total otDuration
.
The date value should not be provided in code, I need to somehow get all the otDuration
values.
Upvotes: 0
Views: 1125
Reputation: 1
For me it worked by using the 'cloud firestore' package. This is part of my code adapted for your use case, hope it works
import 'package:cloud_firestore/cloud_firestore.dart';
DocumentReference employeeAttendance = Firestore.instance.collection('employee')
.document(emp_ID)
.collection('attendance')
.document('2020-7-5');
employeeAttendance.get().then((documentSnapshot) {
String isPresent = documentSnapshot.data['isPresent'].toString();
}
Upvotes: 0
Reputation: 600110
If you attach a listener to that reference, you'll get a DataSnapshot
with all data under the location. Whenever you know the name of a child node/property, you can access it with child("name")
. Whenever you don't know the name of the child nodes, you can loop over the DataSnapshot.getChildren()
on that level.
So something like:
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dateSnapshot: dataSnapshot.getChildren()) {
Log.i("Firebase", dateSnapshot.getKey()); // "2020-7-5", "2020-7-6"
Log.i("Firebase", dateSnapshot.child("otDuration").getValue(String.class)); // "0", "1.5"
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
To then sum the values, the loop would be something like:
double sum = 0.0;
for (DataSnapshot dateSnapshot: dataSnapshot.getChildren()) {
String value = dateSnapshot.child("otDuration").getValue(String.class));
sum += Double.parseDouble(value);
}
Log.i("Sum", String.valueOf(sum));
A few things to consider:
DateFormatter
.otDuration
values as strings, but want to do calculations on them. I recommend storing them as numeric values, so that you don't have to convert back and forth from strings to numbers.Upvotes: 2