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

时间:2018-09-29 10:50:01

标签: java android firebase firebase-realtime-database

我在Firebase中有一个名为 quotes 的节点。我在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的报价?

1 个答案:

答案 0 :(得分:1)

如果您的数据库中有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
        );
    );
);