gpt4 book ai didi

java - Firebase - 如何枚举所有子值的内容?

转载 作者:行者123 更新时间:2023-12-01 19:52:24 24 4
gpt4 key购买 nike

我正在 Android Studio 中开发一个 Android 应用程序,它根据类别(音乐、体育、商业、戏剧)列出事件。每个事件都有名称、描述、地点和时间。这是当用户通过我的应用程序发布事件时事件在 Firebase 中的存储方式:
Screenshot

我如何检索例如音乐类别中的所有子项及其内容?我有四个字符串数组来显示事件(当前手动),如下所示:

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/

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