如何将实时 Firebase 数据库中的数据提取到数组中?

我创建了一个自定义日历,它使用从 github 链接https://github.com/DeveloperBrothers/Custom-Calendar-View获取的数组“HomeCollection” ,以便在我的 android 应用程序中创建自定义日历。目前,事件数据被硬编码到这个数组中(参见下面的代码片段),但希望从我的 firebase 数据库中获取事件属性,而不是在我创建数据库并保存此类事件数据的地方(参见下面的图片链接)。


HomeCollection.date_collection_arr = new ArrayList<HomeCollection>();

        HomeCollection.date_collection_arr.add(new HomeCollection("2018-11-21", "Winter Table Quiz", "7-10 pm, Clubhouse", "ClubHouse", "Come along to the Winter Table Quiz, €5pp, tables of 4, theres lots of great prizes to be won."));

       HomeCollection.date_collection_arr.add(new HomeCollection("2018-11-03", "u21 Division 1 Training ", "10-11am, Club Grounds", "ClubHouse", "Weekly Division 1 training. Weather dependant."));

        HomeCollection.date_collection_arr.add(new HomeCollection("2018-11-03", "u21 Division 2 Training ", "11-12am, Club Grounds", "ClubHouse", "Weekly Division 2 training. Weather dependant."));

        HomeCollection.date_collection_arr.add(new HomeCollection("2018-11-10", "u21 Division 1 Training ", "10-11am, Club Grounds", "ClubHouse", "Weekly Division 1 training. Weather dependant."));

        HomeCollection.date_collection_arr.add(new HomeCollection("2018-11-10", "u21 Division 2 Training ", "11-12am, Club Grounds", "ClubHouse", "Weekly Division 2 training. Weather dependant."));

谁能帮我将此静态代码更改为我的 Firebase 数据库数据?


四季花海
浏览 99回答 2
2回答

慕斯王

1)你必须在你的代码中获取firebase数据引用DatabaseReference mFireBaseDatabaseReference = FirebaseDatabase.getInstance().getReference();2)然后你添加了firebase监听器来获取数据:mFireBaseDatabaseReference.child("events").addListenerForSingleValueEvent(new ValueEventListener() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void onDataChange(@NonNull DataSnapshot dataSnapshot) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //you can parse the data in your models here like thisfor (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {Event event = childSnapshot.getValue(Event.class);HomeCollection.date_collection_arr.add(event);}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void onCancelled(@NonNull DatabaseError databaseError) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });

潇湘沐

因此,您可以制作一个 Java bean 来保存所有这些数据。您作为对象存储的所有数据的制作getter和方法。setter例如,为对象属性创建getter和setter方法,例如:eventDate、eventDescription 等,并假设您将 bean 命名为EventBean.java.现在使用childEventListener这样的:mDatabaseReference = mFirebaseDatabase.getReference().getChild("event");mDatabaseReference.addChildEventListener(new OnChildEventListener(){@Overridepublic void onChildAdded(DataSnapshot snapshot, String previousChildName){EventBean data = snapshot.getValue(EventBean.class);//now you have got data in the&nbsp;eventbean instanceSystem.out.println(data.getEventDate());}});我希望这就是你要找的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java