After retrieving objects with ValueEventListener, the List does not retain the data

0

I'm doing an Activity, which searches the Firebase for User objects, traversing a HashMap with the ValueEventListener to display the result inside a RecyclerView.

The first Log returns the ArrayList listaJogadores filled correctly. The second Log returns the empty ArrayList, that is, soon after the execution of the ValueEventListener the data is being lost. I've reviewed all the lines, I do not know what may be canceling my search. Can anyone help me?

Grupo is a Model

este.getMembros() returns a HashMap

getUser(id) returns a User object

public void recuperarMembros(){

    // Recupera o time do banco de dados
    valueEventListenerTime = timeRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Grupo este = dataSnapshot.getValue(Grupo.class);
            membros = este.getMembros();
            for (String key : membros.keySet()){
                Boolean value = membros.get(key);
                listaJogadores.add(getUser(key));
            }

            Log.d("Resultado_primeiro", listaJogadores.toString());

            adapter.notifyDataSetChanged();

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    Log.d("Resultado_segundo", listaJogadores.toString());

}

As Rosary clarified that the search in Firebase is asynchronous, I changed my code to assign the value to the ArrayList outside of the ValueEventListener so that the data persisted.

The getUser(id) method is now the listAddUser(id) that instead of returning a User object, it assigns it directly to the ArrayList, so the data persists as I expected.

Thank you for the help. The code looks like this:

public void recuperarTime() {

    // Recupera o time do banco de dados
    valueEventListenerTime = timeRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            time = dataSnapshot.getValue(Grupo.class);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}


public void recuperarMembros() {

    listaJogadores.clear();

    membros = time.getMembros();
    if (membros == null) {
        // Intent para MainActivity
        Util.irPara(TimeActivity.this, MainActivity.class, true); 
    } else {
        for (String key : membros.keySet()) {
            Boolean value = membros.get(key);
            if (value) {
                listaAddUser(key);
            }
        }
    }
    adapter.notifyDataSetChanged();

}


/* Recupera usuário pelo ID */
public void listaAddUser(String id) {

    DatabaseReference database = ConfigFirebase.getDatabase();
    DatabaseReference usuarios = database.child("usuarios").child(id);
    usuarios.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            listaJogadores.add(dataSnapshot.getValue(Usuario.class));

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}
    
asked by anonymous 24.05.2018 / 05:20

1 answer

0

Data is not getting lost. They just never were there. This is because Firebase reads data asynchronously .

Due to the asynchronous behavior, the second Log is called before the ArrayList is filled (so it appears empty).

If you need to do any other operation using the ArrayList, do this operation within the ValueEventListener (the same way you did the first log). So you have the guarantee that the data has already been read and inserted into the ArrayList.

    
24.05.2018 / 21:25