作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在 Android Studio 中开发一个 Android 应用程序,它根据类别(音乐、体育、商业、戏剧)列出事件。每个事件都有名称、描述、地点和时间。这是当用户通过我的应用程序发布事件时事件在 Firebase 中的存储方式:
我如何检索例如音乐类别中的所有子项及其内容?我有四个字符串数组来显示事件(当前手动),如下所示:
String[] name = {"Eminem","Rihanna"};
String[] desc = {"Concert","Live Show"};
String[] location = {"Miami","Florida"};
String[] time = {"bllablla","bllablla"};
我想从 firebase 自动填充字符串数组,但是我不确定如何从 Music 元素获取每个子元素的内容?如果需要,我也可以发布填充数据库的 Java 代码。
编辑:我已经尝试过:
DatabaseReference info = FirebaseDatabase.getInstance().getReference("Events").child("Music");
info.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot val: dataSnapshot.getChildren()) {
// Retreive all Music childs and then retreive all data of them childs?
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
最佳答案
可能没有比下载所有音乐数据、循环所有子项并手动创建相应数组更简单的解决方案了 -
1) 创建一个类来将您的 Firebase 音乐记录映射到 -
class MusicRecord{
String date;
String eventDescription;
String eventName;
String location;
}
2) 加载数据、循环子项、检索 MusicRecords 并填充数组
protected void loadData(){
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Events").child("Music");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> recordsSnaphots = dataSnapshot.getChildren();
int count = (int) dataSnapshot.getChildrenCount();
int i = 0;
String[] names = new String[count];
String[] descriptions = new String[count];
String[] locations = new String[count];
String[] times = new String[count];
for(DataSnapshot recordSnapshot: recordsSnaphots){
MusicRecord record = recordSnapshot.getValue(MusicRecord.class);
if(record != null) {
names[i] = record.eventName;
descriptions[i] = record.eventDescription;
locations[i] = record.location;
times[i] = record.date;
i++;
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
关于java - Firebase - 如何枚举所有子值的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50936776/
我是一名优秀的程序员,十分优秀!