Skip to content Skip to sidebar Skip to footer

Custom Object Retrieved From Firebase Always Has Null Attributes

I'm trying to retreive a custom User object from Firebase as follows: getUserFromDB(loggedInUserEmail); viewModel = new ViewModelProvider(this).get(UserViewModel.class); viewModel.

Solution 1:

Loading the user from the database is an asynchronous operation. While the data is being loaded, the main code continues and your viewModel.sendUser(loggedInUser) executes before the data is loaded. Then the success callback is fired and sets loggedInUser, but by that time the view model has already been initialized with the wrong value.

The rule is always quite simple: any code that needs data from the database, needs to be inside the success listener (or be called from there). So something like:

publicvoidgetUserFromDB(String userEmail) {
    DocumentReference docRef = db.collection("users").document(userEmail);
    docRef.get().addOnSuccessListener(documentSnapshot -> {
        loggedInUser = documentSnapshot.toObject(User.class);
        // 👈 Initialize ViewModelProvider here
        viewModel = new ViewModelProvider(this).get(UserViewModel.class);
        viewModel.sendUser(loggedInUser);
    });
}

Also see:

Post a Comment for "Custom Object Retrieved From Firebase Always Has Null Attributes"