I recently started working with Firebase and am still learning what can be done by reading the available documentation. But one problem I'm having is in recovering the data inside a function. The problem in question is that to recover data from the database in the firebase it is necessary to create a ValueEventListener
that implements the onDataChange
and onCancelled
methods and within the onDataChange
method retrieve the data using the variable of type DataSnapshot
. The problem is that I can not assign the result of the getValue()
method to my usuario
variable created outside the OnDataChange
method. If I create the variable inside the method, it works without problems, but with the variable out I can not do the assignment. I believe this is caused because the methods run asynchronously (I think). Would anyone know of any way I could do this assignment? I need this variable to perform other tasks in my app. Here is the code below:
public class FireBaseDB{
private DatabaseReference mDatabase;
public FireBaseDB(){
mDatabase = FirebaseDatabase.getInstance().getReference();
}
public Usuario recuperarUsuarioDoBanco(String userId){
mDatabase.child("users").child(userId);
Usuario usuario;
ValueEventListener listener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
usuario = dataSnapshot.getValue(Usuario.class); //não funciona
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "Ação Cancelada", databaseError.toException());
}
};
mDatabase.addValueEventListener(listener);
return usuario;
}
}