简体   繁体   中英

is there any way to fetch records from firebase realtime database whose attribute has a value in my predefined list?

Basically what I am trying to do is I have a database with the name users having an attribute username . I have some usernames in one list and I want to show details of these users only whose username is present in the list. How can I write a query to fetch details of those users only whose username is found in this list? And note that there is no lexicographical ordering so i can't use startAt() and endAt() functions as well.
code snippet:
=> myList contains usernames.
This code doesn't yield accurate results. Any help would be really appreciated! Thank you!

FirebaseRecyclerOptions<MainModel> options =
                    new FirebaseRecyclerOptions.Builder<MainModel>()
                            .setQuery(FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username")
                                    .startAt(myList.get(0)).endAt(myList.get(myList.size()-1)),MainModel.class).build();

As already mentioned in the comment, the Firebase-UI library doesn't help in your case, because it doesn't allow you to pass multiple queries to the FirebaseRecyclerOptions object. So you need to perform a separate query and use the combined result.

When you are calling .get() on a Firebase Realtime Database query object, you are getting back a Task object. So the key to solving this problem is to use whenAllSuccess(Collection> tasks) . In your case, it should look like this:

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = db.child("users");
Query query = usersRef.orderByChild("username");

List<Task<DataSnapshot>> tasks = new ArrayList<>();
for (String username : myList) {
    tasks.add(query.equalTo(username).get());
}

Tasks.whenAllSuccess(tasks).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
    @Override
    public void onSuccess(List<Object> list) {
        //Do what you need to do with your list.
        for (Object object : list) {
            MainModel mm = ((DataSnapshot) object).getValue(MainModel.class);
            if(mm != null) {
                Log.d("TAG", mm.getUsername());
            }
        }
    }
});

Assuming that you have in your MainModel class a getter called getUsername() , the result in your logcat will be all the usernames of all returned children.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM