0
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 recovering the data within a function. The problem in question is that to recover database data in firebase it is necessary to create a ValueEventListener
implementing the methods onDataChange
and onCancelled
and within the method onDataChange
recover the data using the type variable DataSnapshot
. The problem is that I cannot assign the result of the method getValue()
to my variable usuario
created outside the method OnDataChange
. If I create the variable within the method, it works smoothly, but with the variable outside I can’t do the assignment. I believe this is caused because the methods are executed asynchronously (I think). Would anyone know any way I could do this assignment? Because I need this variable to perform other tasks in my app. The code referred to 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;
}
}
Is there any way to place the section where you assign mDatabase? I believe the problem is in the reference, but without the attribution I can’t say.
– Grupo CDS Informática
@Grupocdsinformática sorry for the delay, I was traveling and only came back this week. I just edited the question with the code snippet you requested.
– CloudAC
No problem. It may be that the userid was not put as key. So it may be coming null. Take a look at the Firebase structure if the key of the key is equal. Also try instead of using as Child, point the reference directly to key
– Grupo CDS Informática
@Grupocdsinformática I think I ended up explaining my problem in the wrong way. The problem is not that the user reference is being null, the problem is that the Android Studio IDE itself mentions that there is a syntax error in the code. Basically, it shows syntax error saying that the user variable does not exist. It is as if what is inside the
onDataChange
do not "see" the outside scope, which in this case is where the variable is being created. I tried to put the modifierfinal
in the variable declaration, but still with the same problem. Do you have any idea what might be?– CloudAC
Sets the user variable to a global of the class. See if it solves.
– Grupo CDS Informática