0

I am making a basic sports statistics Android app using Firebase and I'm not sure how to filter the database base when reading. My database is structured like below, how would I filter a search so I only get parents who contain children of team1:redsox and team2:yankees while ignoring game3?

Database image:

Database image here

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
joe p
  • 41
  • 1
  • 5
  • Firebase Database queries can only order/filter on a single property. In many cases it is possible to combine the values you want to filter on into a single (synthetic) property. You could for example add a property `"teams": "red sox_yankees"` and then filter on that. For an example of this and other approaches, see my answer here: http://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase – Frank van Puffelen Jul 21 '18 at 14:25

1 Answers1

1

Assuming that game1, game2 and game3 nodes are direct children of your Firebase database root, to solve this, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String team1 = ds.child("team1").getValue(String.class);
            String team2 = ds.child("team2").getValue(String.class);
            if(team1.equals("redsox") && team2.equals("yankees")) {
                Log.d("TAG", "Foaund only: team1:redsox and team2:yankees");
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
rootRef.addListenerForSingleValueEvent(valueEventListener);

But note, team1 in game1 is red sox (two words) and in the game2 is redsox (single word). In order to make the equals() method work, both properties should hold the same value, either red sox or redsox.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193