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) {
}
});
}