After recovering the objects with Valueeventlistener the List does not retain the data

Asked

Viewed 132 times

0

I’m doing an Activity, which searches in Firebase the User objects, traversing a Hashmap with Valueeventlistener to display the result inside a Recyclerview.

The first Log returns the Arraylist listaJogadores filled out correctly. The second Log returns the empty Arraylist, that is, soon after the execution of the Valueeventlistener the data is getting lost. I’ve gone through all the lines, I don’t know what might be overriding 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 Rosario clarified that the Firebase search is asynchronous, I changed my code to assign the value to Arraylist outside of Valueeventlistener so that the data persisted.

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

Thank you so much for your 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) {

        }
    });

}

1 answer

0


The data is not getting lost. They’ve simply never been there. That’s because Firebase reads data asynchronously.

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

If you need to do some more operation using Arraylist, do this operation inside Valueeventlistener (the same way you did the first log). So you have the guarantee that the data has already been read and entered in Arraylist.

  • 1

    Thank you Rosary - Based on your clarification, I edited my getUser to, instead of returning a User, assign it directly to Arraylist and worked as expected.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.