rut_0_1
rut_0_1

Reputation: 761

Change a single Firebase value based on the query of another value

My Firebase Database looks like this

enter image description here

I wish to change the event_user_image value by querying the data and comparing the value of event_username. My code looks like this

final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference dr = database.getReference().child("ApprovedEvents");
        dr.orderByChild("event_user_name").equalTo("username");
        dr.child("event_user_image").setValue("https://lh4.googleusercontent.com/aaaaaaaaaaaaaaaa/photo.jpg");

Instead it makes a separate value under Approved Events. Please help !

Upvotes: 0

Views: 1147

Answers (1)

Kurt Acosta
Kurt Acosta

Reputation: 2557

Your DatabaseReference is referring to ApprovedEvents and when you set the value for event_user_image, it would have it like this:

ApprovedEvents
---Record 1
---Record 2
.
.
.
---event_user_image

What you want to do is change the event_user_image for a specific record.

To do that, you first have to query the record with the specific username like this:

final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference dr = database.getReference().child("ApprovedEvents");
Query query = dr.orderByChild("username").equalTo("yourUsername");

Then you could use a listener to see if there would be objects queried with that specific username then get their keys so you could add it in the path for updating:

query.addChildEventListener(
        new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                //dr would refer to path                  : ApprovedEvents
                //adding the key as a child would make it : ApprovedEvents/Record1
                dr.child(dataSnapshot.getKey()).child("event_user_image").setValue("yourDesiredValue");
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            }
        });

Upvotes: 1

Related Questions