2
I’m trying to read data from users who are saved in Firebase, through an Android application. I’m always having null
in Textviews, but I see the value in Android Studio’s Logcat.
I’ve checked my security rules and they allow data reading.
This is my class connecting with 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 her so:
Usuario usuario = new FirebaseBD().lerUsuarioPorId("usuarioTeste");
txtNome.setText(usuario.getNome());
txtEmail.setText(usuario.getEmail());
The method for creating a new User works. Only the methods for reading data return null. Something different is happening in the ValueEventListener
?