I am making a chat app, and I have a Firebase with following Structure. Chat1,Chat2,Chat3... is used for saving data of different Chat groups. Message1,Message2,Message3 are Messages inside 1st group., It can be from any author.
Chats
I want to retrieve the list of all Messages from "Author 1". Meaning Message1,Message3 should be retrieved from Chat1 and Message3 also should get retrieved from Chat2. I want to display all messages from 1 author.
ref = new Firebase(FIREBASE_URL); //Root URL
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
for (DataSnapshot childd : child.getChildren()) {
//This might work but it retrieves all the data
}
}
}
@Override
public void onCancelled() {
}
});
This Gives me entire data! How do I restrict it to "Author1"?
Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.
Firebase will always retrieve the complete node(s) that you ask for. Since you're asking for all Chats or an entire Chat at once (it isn't clear which one you do from your code), that's what you get.
If you want to get less data from Firebase, you'll have to be more specific in what you ask from it. For example if you want to display Chat1, then start by listening for the children of the Chat1 node.
This snippet comes from the Firebase guide for Android:
// Retrieve new posts as they are added to Firebase
ref.addChildEventListener(new ChildEventListener() {
// Retrieve new posts as they are added to Firebase
@Override
public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
Map<String, Object> newPost = (Map<String, Object>) snapshot.getValue();
System.out.println("Author: " + newPost.get("author"));
System.out.println("Title: " + newPost.get("title"));
}
//... ChildEventListener also defines onChildChanged, onChildRemoved,
// onChildMoved and onCanceled, covered in later sections.
});
This snippet accomplishes the same as your current example, but instead of your code looping over the data with a for
, Firebase feeds you the data one message at a time.
With that in place, you can filter the messages. This is a two-step process: first you order by a child node, then you limit which nodes are returned.
Query query = ref.orderByChild("Author").equalTo("Author1", "Author");
query.addChildEventListener(new ChildEventListener() {
// the rest of the code remains the same as above
This last bit is best explained in the Firebase documentation on queries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With