I have a simple android application in which I am using Firebase Realtime Database to store the details of the signed in User.
Here is the User object that I am storing in the database:
public class User {
private UserType userType;
private String phoneNumber;
private String fullName;
private String email;
// addresses are stored as HOSTEL.ROOMNUMBER format
private String hostelAddress;
public User(UserType userType, String phoneNumber, String fullName, String email, String hostelAddress) {
this.userType = userType;
this.phoneNumber = phoneNumber;
this.fullName = fullName;
this.email = email;
this.hostelAddress = hostelAddress;
}
// required for realtime Database
public User() {
}
// getters and setters for all fields...
}
Everytime A user signs in successfully (verified by Firebase Auth), I create a User object and store it as a value against the UID of the user as a key in the database. Everything upto this part works as expected.
Here is what that looks like:
{
"users": {
"<UID>": {
"email": "<email>",
"fullName": "<full name>",
"hostelAddress": "<address>",
"phoneNumber": "<number>",
"userType": "CUSTOMER"
}
}
}
Now, I want to have a User Object, stored locally, that is synced with the User object stored in the database that corresponds to the currently signed user.
I want to access this User Object in different activities of my app.
For this I have made a separate class to interact with the database:
abstract public class FirebaseUtil {
public static FirebaseDatabase database;
public static User currentUserObject;
public static String getCurrentUserID()
{
return FirebaseAuth.getInstance().getUid();
}
public static DatabaseReference getCurrentUserReference()
{
return database.getReference("users").child(getCurrentUserID());
}
static
{
database = FirebaseDatabase.getInstance();
fetchCurrentUser();
}
public static void fetchCurrentUser()
{
if (getCurrentUserID()==null)
{
return;
}
getCurrentUserReference().addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
currentUserObject = snapshot.getValue(User.class);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
// Store user inside database, with the key as its UID.
public static void storeUser(User user, String UID)
{
database.getReference("users").child(UID).setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
fetchCurrentUser();
}
});
}
}
The problem is that this approach does not work, whenever I try to use the currentUserObject
in another class in the app, its always null
, even though the getCurrentUserID()
method successfully returns the logged in User UID.
I haven’t tried many things since I have no idea at all why this could not be working.
I will appreciate any push in the right direction.
And if there is a better, more reliable way to achieve this task, please let me know.