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

时间:2018-06-19 20:52:21

标签: java android firebase firebase-realtime-database

我正在Android Studio中开发一个Android应用,该应用会根据类别(音乐,体育,商业,戏剧)列出事件。每个事件都有名称,描述,位置和时间。当用户通过我的应用发布事件时,事件是如何存储在Firebase中的:
Screenshot

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

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) {
     }

3 个答案:

答案 0 :(得分:1)

根据您的帖子,您需要做几件事:

  1. 创建模型

您将必须创建一个POJO,以描述Firebase实时数据库中数据的结构。根据您的情况,创建一个类FirebaseEvent,该类具有一个Date和三个字符串(eventDescription,eventName,location)。

  1. 实例化课程

根据您的最后一个片段,使用Firebase实时数据库中的数据实例化您的类。 Firebase API对此仍然有些乏味,但这仍然是最常用的方法

@Override
public void onDataChange(DataSnapshot dataSnapshot) {   
    GenericTypeIndicator<HashMap<String,FirebaseEvent>> ti = 
        new GenericTypeIndicator<HashMap<String,FirebaseEvent>>() {};

    HashMap<String,FirebaseEvent> retrievedEvents = childSnapshot.getValue(ti);
}

现在,您拥有的是一个HashMap,其中包含诸如“ Eminem”和“ Rihanna”之类的键,并且对应的值为FirebaseEvent

答案 1 :(得分:1)

可能没有比下载所有音乐数据,遍历所有子级并手动创建相应数组简单的解决方案-

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) {

        }
    });
}

答案 2 :(得分:1)

我选择对动态数据结构使用ArrayList。 我还为数据库拍摄了快照: enter image description here

public class MainActivity extends AppCompatActivity {
    List<String> name= new ArrayList<String>();
    List<String> location= new ArrayList<String>();
    List<String> date= new ArrayList<String>();
    private DatabaseReference mDatabase;
    public static final String TAG= "YOUR-TAG-NAME";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Events").child("Music");
        // Read from the database
        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                for (DataSnapshot values: dataSnapshot.getChildren()) {
                    //query for the parent of the date "Eminem"
                    String key = values.getKey().toString();
                    name.add(key);
                    //query for location in the music category
                    date.add(values.child("location").getValue().toString());
                    //query for date in the music category
                    date.add(values.child("date").getValue().toString());
                }
            }
            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });
        }
}