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