简体   繁体   English

Firebase查询不会显示所有数据

[英]Firebase Query don't show all the data

I need to get all users of a determined age range, but my code does not work. 我需要确定年龄段的所有用户,但是我的代码无法正常工作。

My Firebase database structure is this. 我的Firebase数据库结构是这样。

-user
   -1
      -name:"James"
      -age:"21"

   -2
      -name:"Artur"
      -age:"25"

   -3
      -name:"Charlotte"
      -age:"25"

   -3
      -name:"Marvin"
      -age:"80"

My code is this. 我的代码是这个。 With this I just catch 1 user. 有了这个,我只抓到1个用户。

DatabaseReference uRef = database.getReference("users");

Query UserQuery = uRef.orderByChild("age").startAt(21).endAt(50);

    UserQuery.limitToFirst(10).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            int counter =(int) dataSnapshot.getChildrenCount();

            Log.d("TAG////////", String.valueOf(counter));




        }


        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

But if I delete the endAt() condition, I catch all users after 21 and I just wanna catch the users in the range. 但是,如果删除endAt()条件,则会在21点之后捕获所有用户,而我只想捕获范围内的用户。

DatabaseReference uRef = database.getReference("users");

Query UserQuery = uRef.orderByChild("age").startAt(21); //I deleted endAt(50);

    UserQuery.limitToFirst(10).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            int counter =(int) dataSnapshot.getChildrenCount();

            Log.d("TAG////////", String.valueOf(counter));




        }


        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Please help me. 请帮我。

It looks like you store the age as a string value, so you should also pass a string into the query: 看起来您将年龄存储为字符串值,因此还应该将字符串传递给查询:

Query UserQuery = uRef.orderByChild("age").startAt("21").endAt("50");

Note that this will lead to problems when you want to get everyone from age 2 to 5, since in lexicographical sorting that looks like: 请注意,当您要让每个人的年龄都在2岁到5岁之间时,这将导致问题,因为在字典编排排序中如下所示:

"18"
"19"
"2"
"20"
"21"
"22"
...
"29"
"3"
"30"
"31"
...

So you'll probably want to fix that by storing the ages as actual numeric values, instead of storing them as a string. 因此,您可能需要通过将年龄存储为实际数字值而不是将其存储为字符串来解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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