I am trying to return data in a method that I get from a listener for single event call. However, it looks like the object I'm returning is being populated after the actual return statement. I understand that the call to get the data snapshot is asynchronous and that is why this is happening. How can I avoid this? I've tried Semaphores and Atomic Booleans but it just seems to lock up my application. Here is the code in question.
static User getUser(String uid){
/**** created final object here for returning ****/
final User returnUser = new User();
Firebase userRef = new Firebase("<firebase-url>/users/"+uid+"/");
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("MT", "attempting to instantiate user");
User tempUser = dataSnapshot.getValue(User.class);
/**** preparing object for return ****/
returnUser.setNickname(tempUser.getNickname());
returnUser.setAge(tempUser.getAge());
returnUser.setEmail(tempUser.getEmail());
returnUser.setHeight(tempUser.getHeight());
returnUser.setSex(tempUser.getSex());
returnUser.setWeight(tempUser.getWeight());
//This logs actual information
Log.d("MT", returnUser.getNickname() + " =======INSTANTIATED=======.");
Log.d("MT", returnUser.getEmail());
Log.d("MT", new Double(returnUser.getAge()).toString());
Log.d("MT", new Double(returnUser.getHeight()).toString());
Log.d("MT", returnUser.getSex());
Log.d("MT", new Double(returnUser.getWeight()).toString());
}
@Override
public void onCancelled(FirebaseError firebaseError) {
Log.d("MT", "Something went wrong.");
}
});
Log.d("MT", returnUser.getNickname()); //This logs an empty string.
return returnUser;
}
Note: I've tried Atomic boolean set to false then set to true within the listener and then have a while(boolean == false) before I return but this results in a lockup of my application.