gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 18:43:13 25 4
gpt4 key购买 nike

我在 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 的报价单?

最佳答案

如果你的数据库中有超过 4 条记录,要解决这个问题,你可以使用一个查询,你应该在其中结合 startAt()endAt() 方法像这样限制查询的两端:

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

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

Create a query constrained to only return child nodes with a value greater than or equal to the given value, using the given orderBy directive or priority as default.

这里是关于 Firebase 查询的 endAt() 的更多信息方法:

Create a query constrained to only return child nodes with a value less than or equal to the given value, using the given orderBy directive or priority as default.

编辑:根据您的评论,如果您只想要将 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
);
);
);

关于java - Firebase 查询以获取给定范围内的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52567616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com