I'm trying to read data from users that are stored in Firebase through an Android application. I'm always having null
in TextViews, but I see the value in the Logcat of Android Studio.
I have already checked my security rules and they allow you to read data.
This is my class that connects to Firebase:
public class FirebaseBD {
private DatabaseReference ref;
private Usuario usuario = null;
private List<Usuario> listaUsuarios = null;
public FirebaseBD(){
ref = FirebaseDatabase.getInstance().getReference();
}
public void novoUsuario(Usuario usuario){
ref.child("usuarios").push().setValue(usuario);
}
public Usuario lerUsuarioPorId(String idUsuario){
ref.child("usuarios").child(idUsuario)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
usuario = dataSnapshot.getValue(Usuario.class);
Log.i(this.getClass().getSimpleName(),
usuario.toString());
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
return usuario;
}
public List<Usuario> lerUsuarios(){
ref.child("usuarios")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
listaUsuarios = new ArrayList<>();
for(DataSnapshot snapshot : dataSnapshot.getChildren())
{
listaUsuarios.add(snapshot.getValue(Usuario.class));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
return listaUsuarios;
}
}
And in my MainActivity I'm calling it like this:
Usuario usuario = new FirebaseBD().lerUsuarioPorId("usuarioTeste");
txtNome.setText(usuario.getNome());
txtEmail.setText(usuario.getEmail());
The method for creating a new User works. Only methods to read data are returned null. Is there something different happening in ValueEventListener
?