繁体   English   中英

Firebase查询以获取给定范围内的数据

[英]Firebase query to fetch data in given range

我在Firebase中有一个称为引号的节点。 我在Android中获取特定范围的数据时遇到问题。 我想从2开始获取3个连续的引号id。这是我的查询数据库:

"quotes" : {
"-L75elQJaD3EYPsd4oWS" : {
  "authorName" : "Hellen v",
  "famousQuote" : "When one door of happiness closes, another opens; but often we look so long at the closed door that we do not see the one which has been opened for us.",
  "id" : "1",
  "uploadedBy" : "Admin"
},
"-L7GOvDNI-o_H8RvNwoN" : {
  "authorName" : "Rocky Balboa",
  "famousQuote" : "It's not about how hard you can hit; it's about how hard you can get hit and keep moving forward.",
  "id" : "2",
  "uploadedBy" : "Admin"
},
"-L7GP9oBv5NR1T6HlDd4" : {
  "authorName" : "African proverb",
  "famousQuote" : "If you want to go fast, go alone. If you want to go far, go together.",
  "id" : "3",
  "uploadedBy" : "Admin"
},
"-L7GPjM1F3_7Orcz0Q1q" : {
  "authorName" : "A.P.J Abdul Kalam",
  "famousQuote" : "Don’t take rest after your first victory because if you fail in second, more lips are waiting to say that your first victory was just luck.",
  "id" : "4",
  "uploadedBy" : "Admin"
},

以下是我用于报价的规则

"quotes": {
 ".indexOn": ".value"
}

如何获得ID为2,3和4的报价?

如果您的数据库中有4条以上的记录,则可以使用以下查询来解决此问题:在该查询中,应结合使用startAt()endAt()方法来限制查询的两端,如下所示:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("quotes").orderByChild("id").startAt("2").endAt("4");
query.addListenerForSingleValueEvent(/* ... */);

请在此处查看有关Firebase Query的startAt()方法的更多信息:

使用给定的orderBy指令或优先级作为默认值,创建一个约束以仅返回值大于或等于给定值的子节点的查询。

以下是有关Firebase Query的endAt()方法的更多信息:

使用给定的orderBy指令或优先级作为默认值,创建一个约束以仅返回值小于或等于给定值的子节点的查询。

编辑:根据您的评论,如果只希望将id属性设置为2、3和4的项目,则应使用如下嵌套查询:

Query queryTwo = rootRef.child("quotes").orderByChild("id").equalsTo("2");
queryTwo.addListenerForSingleValueEvent(
    List<Item> list = new ArrayList();
    list.add(itemTwo);
    Query queryThree = rootRef.child("quotes").orderByChild("id").equalsTo("3");
    queryThree.addListenerForSingleValueEvent(
        list.add(itemThree);
        Query queryFour = rootRef.child("quotes").orderByChild("id").equalsTo("4");
        queryFour.addListenerForSingleValueEvent(
            list.add(itemFour);

            //Do what you need to do with the list that contains three items
        );
    );
);

暂无
暂无

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

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