Asuwathaman R C
Asuwathaman R C

Reputation: 303

Android Firebase Database get value

I want to get data from firebase realtime database.

Firebase Databse

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

Answers (2)

Juan Santos
Juan Santos

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

Frank van Puffelen
Frank van Puffelen

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:

  • I'd highly recommend padding the values in your date, so that they become "2020-07-05" and "2020-07-06". This will make potential future queries much more likely. If you want to do this, I'd recommend looking into Java's DateFormatter.
  • You're storing your 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

Related Questions