Firebase Android, checking if an object (with multiple children) exists

前端 未结 3 1768
野性不改
野性不改 2021-01-24 09:20

I am using a Firebase Database to store user’s reports. Each user is allowed to submit only 10 different reports.

In the example below we have a user named “Jasna Kulja

3条回答
  •  终归单人心
    2021-01-24 09:34

    Firebase queries can only order/filter by a single property. So there is no WHERE clause within Firebase. What should you do instead, is to couple a compound value named location_mode_spinnerOne. Your database structure should look like this:

    Firebase-root
       |
       -- Students Reports
             |
             -- Jasna Kuljancic
                   |
                   -- Clinical First
                         |
                         -- -KuVRQ4OjdfKXCNdLWzb
                                |
                                --- data: 3939393
                                |
                                --- location: "fifififi"
                                |
                                --- mode: "ododododo"
                                |
                                --- spinnerOne: "Asylum Hill Family Clinic"
                                |
                                --- location_mode_spinnerOne: "fifififi_ododododo_Asylum Hill Family Clinic"
    

    As you probably see, i have added the new compound value location_mode_spinnerOne for each particular category. This means that you can query your Firebase database according to this new location_mode_spinnerOne field. Assuming that the above database structure is correct, please use the following code:

    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference categoryRef = rootRef.child("Students Reports").child(fullname).child(CATAGORY);
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String searchedText = "fifififi";
    
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                String location_mode_spinnerOne = ds.child("location_mode_spinnerOne").getValue(String.class);
                if(!location_mode_spinnerOne.contains(searchedText)) {
                    categoryRef.child(uniqueID).setValue(subreport);
                }
            }
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    categoryRef.addListenerForSingleValueEvent(eventListener);
    

    I gave you an example for searching fifififi keyword. The searchedText text would be the exact searched text typed by the user.

    To better understanding, i suggest you see this tutorial.

提交回复
热议问题