Home > OS >  How to Filter Data In Firebase realtime Database
How to Filter Data In Firebase realtime Database

Time:06-10

I want to take the data of the child called news to a list. Can I get the department key only when all or Management?

Here is my code:

query = MainNewsDb.orderByChild("department").equalTo("Management").limitToLast((int)limit);
query.addValueEventListener(valueEventListener1);

query1 = NewsListDb1.orderByChild("department").equalTo("all").limitToLast((int)limit);
query1.addValueEventListener(valueEventListener1);

This Is My RTDB:

enter image description here

CodePudding user response:

To get the combined result of two separate Firebase Realtime Database queries, I recommend you to use Tasks.whenAllSuccess() method. You can achieve this, using the following lines of code:

query = MainNewsDb.orderByChild("department").equalTo("Management").limitToLast((int)limit);
query1 = NewsListDb1.orderByChild("department").equalTo("all").limitToLast((int)limit);

Task firstTask = query.get();
Task secondTask = query1.get();

Task combinedTask = Tasks.whenAllSuccess(firstTask, secondTask).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
    @Override
    public void onSuccess(List<Object> list) {
         //Do what you need to do with your list
    }
});

As you can see, when overriding the "onSuccess()" method the result is a list of objects. As soon as you have it, simply map each object from the list into an object of the desired type.

  • Related