Issue
After register with Firebase phone number (sms), I can get user_id
and friends list from user_id
, etc. But after I exit from app, and then re-enter the app return null (FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();)
I cannot not get Firebase user id
(firebaseUser return null). implementation 'com.google.firebase:firebase-auth:21.0.1'
Plz... How to solve a problem?
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) { // return null
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
reference1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NotNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
}
@Override
public void onCancelled(@NotNull DatabaseError databaseError) {
}
});
}
Solution
Firebase automatically restores the user credentials when you restart the app. This requires it to make a call to the server, amongst others to check whether the account was disabled. Since this call may take some time to complete, most likely it's still ongoing when you call FirebaseAuth.getInstance().getCurrentUser()
.
For this reason it's best to instead observe FirebaseAuth.instance.authStateChanges()
as shown in the https://stackoverflow.com/collectives/google-cloud/articles/68104924/listen-for-authentication-state-in-android. This callback gets called first when the authentication check I mentioned has completed, so you can use that to respond to the restored sign-in:
auth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
Log.i("firebase", "AuthState changed to null");
}
else {
Log.i("firebase", "AuthState changed to "+firebaseAuth.getCurrentUser().getUid());
}
}
});
Answered By - Frank van Puffelen