简体   繁体   中英

Get child from unknown key in android firebase

I have a database which holds timestamped entries for lifestyle quizzes that a user takes. The schema is as follows where the children of the timestamp are key value pairs corresponding to the users inputs.

-EvcKZHBZ4CVo9yAdlP7ldadCZS03
    -2018-03-19 12:19:49
        - age: "20"
        - exercise_total: "0"
        ...
    -2018-03-18 12:32:44
        - age: "20"
        - exercise_total: "15"
        ...

I have an object made called heartScore with member variables corresponding to all of the children of the timestamp. How do I return the data under the first date entry into a object of type heartScore if I don't know the exact date that the quiz was taken?

This should do the trick:

databaseReference.child("userId").limitToFirst(1)

In practice:

    FirebaseReference ref = FirebaseDatabase.getInstance().getReference()
    ref.child(userId).limitToFirst(1).addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for(DataSnapshot snapshot: dataSnapshot.getChildren()){
                            // There will only be one child
                            HeartScore score = snapshot.getValue(HeartScore.class);

                           // Return the HeartScore object in a callback or whatever else you want
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM