我正在尝试检索以某事物开头的孩子的列表。以下是我的Firebase实时数据库中的数据示例:
在图像中,我想检索所有以关键字“ jsonmat”开头的数据。
我正在使用以下代码,但始终返回null:
DatabaseReference db = FirebaseDatabase.getInstance().getReference()
.child("Events");
db.startAt("jsonmat").addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("events", dataSnapshot.toString());
for (DataSnapshot data : dataSnapshot.getChildren()) {
// here the user will have the specified email only
}
}
@Override
public void onCancelled(DatabaseError databaseError){
Log.i("MyApp", "getUser:onCancelled", databaseError.toException());
}
});
答案 0 :(得分:0)
您无法执行的操作。您不能仅对直接子键(-M...
)和嵌套值(active: true
)上的嵌套键进行排序/过滤。
通常,您将要创建一个新的顶级节点,在其中存储要搜索的键,然后为每个匹配的嵌套节点存储推键:
"category_things": {
"jsonmat_jsonmat": {
"-M62....uYgB": true,
"-M62....2-eO": true
}
}
另请参阅:
下面是我的原始但错误的答案...
如果使用 startAt
而不指定orderBy...
子句,则数据将按优先级排序。此优先级是Firebase支持对特定属性进行排序之前的剩余内容,因此大多数情况下,这意味着您必须调用orderBy...
方法,然后才能进行过滤。
所以:
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("Events");
db.orderByKey().startAt("jsonmat").addListenerForSingleValueEvent(new ValueEventListener() {
...
答案 1 :(得分:0)
针对您的情况,您可以在节点Events
的子节点上循环2次:
//the reference to the node Events
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("Events");
db.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//loop 1
for (DataSnapshot data : dataSnapshot.getChildren()) {
//loop2
for (DataSnapshot dataTwo : data.getChildren()) {
//get the key
String key = dataTwo.getKey();
if(key.startsWith("jsonmat")){
//we got a matching key so extract the data and maybe put them in a list
boolean active = dataTwo.child("active").getValue(Boolean.class);
int bet = dataTwo.child("bet").getValue(Integer.class);
String challenger = dataTwo.child("challenger").getValue(String.class);
String competitor = dataTwo.child("competitor").getValue(String.class);
String game = dataTwo.child("game").getValue(String.class);
............
............
............
}else{
//we didn't get a match
}
}//end loop2
}//end loop1
}
@Override
public void onCancelled(DatabaseError databaseError){
Log.i("MyApp", "getUser:onCancelled", databaseError.toException());
}
});