1

Firebase database node "memories/" contains objects of type Memory{String name; int cost; ...} I need to get objects with specific "name" field (for example "party") and delete them or change "cost" field value in other situation. I've tried this...

memoryRef.orderByChild("party").equalTo(true).setValue(null);

error

I've read this...https://firebase.google.com/docs/reference/js/firebase.database.Query

There are only action handlers there... please help, I have feeling It should be simple...

KENdi
  • 7,576
  • 2
  • 16
  • 31

2 Answers2

2

You could use a query:

Query query = memoryRef.orderByChild("name").equalTo("party");
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot){
            for (DataSnapshot child : dataSnapshot.getChildren()) {
                //to update:
                memoryRef.child(child.getKey()).child("cost").setValue(100);
                //delete
                memoryRef.child(child.getKey()).removeValue();
            }
        }
    });

Note: Do remember to set indexOn rule on "name" for Memory

Your rule should looks like this:

{
  "rules": {
    ...
    "memories": {
      ".indexOn": "name"
    }
  }
}
Mark KWH
  • 1,059
  • 1
  • 8
  • 20
  • How do we set the indexOn rule? – Ajil O. Jul 24 '17 at 02:36
  • "Database" -> click on "Rules" tab next to "Data", check here for more info, https://firebase.google.com/docs/database/security – Mark KWH Jul 24 '17 at 02:41
  • Thanks a lot. If you have time please have a look at this [question](https://stackoverflow.com/questions/45207730/updating-firebase-database-with-nodes-created-with-push) – Ajil O. Jul 24 '17 at 02:45
0

There could be more ideal approaches, but this is what works for me:

DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("memories");
    ValueEventListener memListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            memoryList = new ArrayList<>();
            Memory memory;

            for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {

                int cost = (int) userSnapshot.child("cost").getValue();
                String name = (String) userSnapshot.child("name").getValue();
                //Get other fields here

                if (name.matches("party")) {
                    memory = new Memory(name , cost);
                    memoryList.add(memory);
                }

            }


        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };

    mDatabase.addValueEventListener(memListener);

PS: I'm just adding it to an array here... You could change it as you require

Ajil O.
  • 6,562
  • 5
  • 40
  • 72