I want to get data from Firebase and then return ArrayList. I don't want to listen constantly for changes in database. I just want to immediately query database once so i'm using addListenerForSingleValueEvent and i thought that this will allow me to just get data from database and simply return it but the list is unfortunately empty. I tried to update list at the end of onDataChange method but it still doesn't work because the list is empty.
private List<ContactsDTO> contacts = new ArrayList<>();
public void updateContacts(List<ContactsDTO> contacts) {
this.contacts = contacts;
}
public void getContactsDB() {
refContacts.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<ContactsDTO> temp = new ArrayList<>();
for(DataSnapshot child : dataSnapshot.getChildren()) {
ContactsDTO contactDTO = child.getValue(ContactsDTO.class);
temp.add(contactDTO);
}
updateContacts(temp);
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("error");
}
});
}
public List<ContactsDTO> getContacts() {
getContactsDB();
System.out.println("contacts size: " + contacts.size()) // list will be empty
return contacts;
}
// edit:
I get data correctly in onDataChange method so the db structure is not the problem, but as you wish:
Do you have any idea how to achieve it?