我正在尝试编写一个firebase应用程序,其中包含一个简单的ArrayList,它将作为列表视图的提要。 为了做到这一点,我有一个单独的服务FirebaseConnection并将获取数据。然后将该数据送到列表中。问题是数据首先被送到列表为null然后数据完成检索。你可能有什么解决方案吗?
这是我的代码:
public ArrayList< Event > getAllEventsOnFirebase() {
final ArrayList< Event > events = new ArrayList<Event>();
DatabaseReference eventsTable = getDatabaseTableWith(Constants.tableEvents);
eventsTable.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
HashMap<String, Object> event = (HashMap<String, Object>) postSnapshot.getValue();
String eventId = (String) event.get(Constants.taEventUUID);
String eventName = (String) event.get(Constants.taEventName);
String eventAddress = (String) event.get(Constants.taEventAddress);
Event newEvent = new Event(eventId, eventName, eventAddress);
events.add(newEvent);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return events;
}
我填充列表的方式如下:
eventsArray = FirebaseConnection.getInstance().getAllEventsOnFirebase();
EventListAdapter adapter = new EventListAdapter(this, eventsArray);
eventsListView.setAdapter(adapter);
答案 0 :(得分:3)
数据是从Firebase异步加载的。幸运的是,您可以随时填充ArrayList
,只要您通过调用adapter.notifyDataSetChanged()
告诉适配器您已更改它。
public ArrayList< Event > getAllEventsOnFirebase(final EventListAdapter adapter,
final ArrayList<Event> events) {
DatabaseReference eventsTable = getDatabaseTableWith(Constants.tableEvents);
eventsTable.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String eventId = postSnapshot.child(Constants.taEventUUID).getValue(String.class);
String eventName = event.child(Constants.taEventName).getValue(String.class);
String eventAddress = event.child(Constants.taEventAddress).getValue(String.class);
Event newEvent = new Event(eventId, eventName, eventAddress);
events.add(newEvent);
}
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
现在您可以将其命名为:
ArrayList< Event > events = new ArrayList<Event>();
EventListAdapter adapter = new EventListAdapter(this, eventsArray);
eventsListView.setAdapter(adapter);
FirebaseConnection.getInstance().getAllEventsOnFirebase(adapter, events);