j2emanue j2emanue - 1 month ago 9
Android Question

Google firebase realtime database - how to get event updates on only a section of json tree

So imagine i have a firebase json tree that more or less looks like this:

//ignore poorly nested structure as this is an example
{
"chats": {
"one": {
"title": "Historical Tech Pioneers",
"messages": {
"m1": { "sender": "ghopper", "message": "Relay malfunction found. Cause: moth." },
"m2": { ... },
// a very long list of messages
}
},
"two": { ... }
}
}


Now in firebase after i get a instance of the database how can i receive updates only when section "two" is altered. So i'd like to sync on section "two" and ignore changes to "one".

Firebase has a ValueEventListener class that i can use which looks like this:

ValueEventListener postListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

Post post = dataSnapshot.getValue(Chats.class);
// ...this gets me the entire Chats object, i just needs the "two" object
}

@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};


so im having trouble with how i can subscribe to changes to only the "two" event. I do not know how to set the event listener.

Answer

You attach a listener to the node you want to listen to:

DatabaseReference root = FirebaseDatabase.getInstance().getReference();
DatabaseReference sectionTwo = root.child("two");
sectionTwo.addValueListener(...

You can easily see how the sample snippets from our documentation work by clicking the link at the bottom of them. For the snippet you copied from the section on listening for value events that link leads to this file in Github.

Comments