scof93
scof93

Reputation: 389

Firebase how to return data?

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:

enter image description here

Do you have any idea how to achieve it?

Upvotes: 0

Views: 2455

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

This is happening because onDataChange is called asynchronously and the statement return contacts is executed before onDataChange has been called. So in order to use that temp List<ContactsDTO> you need to use it inside the onDataChange() method.

To solve this problem, please visit this post and this post.

Hope it helps.

Upvotes: 3

Related Questions