how to update nodes inside other nodes in firebase Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of how to update nodes inside other nodes in firebase without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Context Hello, I am trying to update an element of a node in firebase with android, the problem is that as seen in the structure of my database, Database I have a node called “comment” and within it another node with a post id and inside the Post ID node is the comment ID.

issue

I do not know how I can update all the nodes that meet certain encodings, since I cannot put an exact path since this would only update one node and I want to update all the nodes that meet the condition of the query as seen in the code.

final DatabaseReference CommentDB = FirebaseDatabase.getInstance().getReference("Comment");
Query quersy = CommentDB.orderByChild("uname").equalTo(currentUsers.getDisplayName());
quersy.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()){
            String key = ds.getKey();
            HashMap<String, Object> maps = new HashMap<>();
            maps.put("uimg", ""+mUri);
            sd.child(key).updateChildren(maps);

Answer

Your uname is nested under two dynamic levels. Firebase Realtime Database can only order/filter on values that are at a fixed path under one dynamic level.

So you will have to either change data structure to be a flat list under /Comment or read all data under /Comment and filter client-side.

final DatabaseReference commentDB = FirebaseDatabase.getInstance().getReference("Comment");
commentDB.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for(DataSnapshot level1Snapshot : dataSnapshot.getChildren()){
            for(DataSnapshot level2Snapshot : level1Snapshot.getChildren()){
                if (currentUsers.getDisplayName().equals(level2Snapshot.child("uname").getValue(String.class)) {
                    Log.i("Firebase", "Updating "+level1Snapshot.getKey()+"/"+level2Snapshot.getKey());
                    level2Snapshot.getRef().child("uimg").setValue(mUri);
                }    
            }    
        }
    }
    ...

We are here to answer your question about how to update nodes inside other nodes in firebase - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji