简体   繁体   中英

Retrieve the same child from multiple children Android Firebase

This is what my database looks like:

数据库

As you can see under "Mjerenja" there are multiple children representing dates. Under every single one of these children, there is a child called the "latest" which holds a true or false value. In this database, there will always be only one latest child with the value true while the rest will always be false. How do I go about retrieving this child, more specifically the "datum" child from the one that holds the "latest" value as true?

Your query can be like this

var MjerenjaRef = firebase.database().ref("Mjerenja/");
MjerenjaRef.orderByChild("latest”).equalTo(True);

there is a child called the "latest" which holds a true or false value.

Seeing your database, the "latest" property holds a value of true or false, but as a String and not as a boolean value. However, if you want to get the item that has the "latest" property set to true , please use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mjerenjaRef = rootRef.child("Mjerenja");
Query latestQuery = mjerenjaRef.orderByChild("latest").equalTo("true");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String datum = ds.child("datum").getValue(String.class);
            Log.d("TAG", datum);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
    }
};
latestQuery.addListenerForSingleValueEvent(valueEventListener);

The output in the logcat will be:

15/11/2020

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