Reputation: 1735
I am trying to write a firebase app that contains a simple ArrayList that will serve as feed for a list view. In order to do so I have a singleton that takes care of FirebaseConnection and will fetch the data. This data is then feeded to the list. The problem is the data is first feeded to the list as null then the data is finished retrieving. Any solutions you might have for me?
Here is my code:
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;
}
Also the way I populate the list is as follows:
eventsArray = FirebaseConnection.getInstance().getAllEventsOnFirebase();
EventListAdapter adapter = new EventListAdapter(this, eventsArray);
eventsListView.setAdapter(adapter);
Upvotes: 1
Views: 3658
Reputation: 600126
Data is loaded asynchronously from Firebase. Luckily you can populate the ArrayList
at any moment, as long as you tell the adapter that you changed it by calling 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();
}
});
}
Now you can call it as:
ArrayList< Event > events = new ArrayList<Event>();
EventListAdapter adapter = new EventListAdapter(this, eventsArray);
eventsListView.setAdapter(adapter);
FirebaseConnection.getInstance().getAllEventsOnFirebase(adapter, events);
Upvotes: 3