Check if user is authenticated for the first time in Firebase Google Authentication in Android
To check if it's the first time user logs in, simply call the AdditionalUserInfo.isNewUser()
method in the OnCompleteListener.onComplete
callback.
Example code below, be sure to check for null.
OnCompleteListener<AuthResult> completeListener = new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
boolean isNew = task.getResult().getAdditionalUserInfo().isNewUser();
Log.d("MyTAG", "onComplete: " + (isNew ? "new user" : "old user"));
}
}
};
Check the docs for more reference AdditionalUserInfo
How can I detect if user first time in Firebase
How can I detect if user first time in Firebase?
If you want to check if the user logs in for the first time, it's the same thing if you check if a user is new. So to solve this, you can simply call AdditionalUserInfo's isNewUser() method:
Returns whether the user is new or existing
In the OnCompleteListener.onComplete
callback like this:
OnCompleteListener<AuthResult> completeListener = new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
if (isNewUser) {
Log.d("TAG", "Is New User!");
} else {
Log.d("TAG", "Is Old User!");
}
}
}
};
For more informations, please see the official documentation.
Edit: In order to make it work, you need to add a complete listener. Please see the code below:
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
if (isNewUser) {
Log.d(TAG, "Is New User!");
} else {
Log.d(TAG, "Is Old User!");
}
}
});
Or even simpler:
mAuth.signInWithCredential(credential).addOnCompleteListener(this, completeListener);
In which, the completeListener
object is the object that was defined first.
Check if the Firebase user is authenticated for the first time using google in Flutter
If the user is signing in for the first time, the AdditionalUserInfo.isNewUser
property will be true.
Note that this property can be a bit finicky in my experience as "first" is a bit too strict. If that is the case for you, you might want to instead compare the creationTime
and lastSigninTime
in the FirebaseUserMetaData
object explicitly to determine whether the user is "new enough".
Check if user is authenticated for the first time with Google Sign-In with Firebase Authentication in Xamarin Android
From Firebase doc, you can check the last sign-in timestamp against the created-at timestamp
public void OnComplete(Task task)
{
if (task.IsSuccessful)
{
FirebaseUser user = auth.CurrentUser;
IFirebaseUserMetadata metadata = auth.CurrentUser.Metadata;
if (metadata.CreationTimestamp == metadata.LastSignInTimestamp)
{
// The user is new, show them a fancy intro screen!
}
else
{
// This is an existing user, show them a welcome back screen.
}
}
else
{
Toast.MakeText(this, "Authentication failed.", ToastLength.Short).Show();
}
}
How to check if a user just Google signed-in for the first time in Firebase
Yay! I found a way which works if data is already present on database or not. It works as I intended,
If I create a new user from google/email, I save their name in real time database, but signing in from same account, earlier was leading to rewriting of new data (Name) on the same place - too much use of data bandwidth.
I fixed by this. It simply checks where data exists there or not and then it further moves ahead.
final User newUser = new User();
newUser.email = user.getEmail();
newUser.name = user.getDisplayName();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("user/" + user.getUid())) {
//User Exists , No Need To add new data.
//Get previous data from firebase. Take previous data as soon as possible..
return;
} else {
FirebaseDatabase.getInstance().getReference().child("user/" + user.getUid()).setValue(newUser);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have one thing to tell you guys, User is a custom class with POJOs to put data at firebase database.
Reply me if this works for you too.
Edit - Firestore
newUser.email = user.getEmail();
newUser.name = user.getDisplayName();
DocumentReference docRef =
db.collection("users").document(user.getUid());
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull
Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
//User Exists , No Need To add new data.
//Get previous data from firebase. Take previous data as soon as possible..
} else {
Log.d(TAG, "No such document");
//Set new data here
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});```
Firebase - check if user created with Google Account is signing up or logging in?
There aren't any separate methods to login
and sign up
when using Google Sign-In or any other provider. If a user with that credential exists then user will be logged in else a new user account will be created. You can then use additionalUserInfo.isNewUser
property from the result received from signInWithPopUp
method to check if the user is new.
firebase.auth().signInWithPopup(provider).then(function (result) {
const {additionalUserInfo: {isNewUser}} = result;
console.log(isNewUser ? "This user just registered" : "Existing User")
})
For the new Modular SDK (V9.0.0+
), the same can be written as:
import { signInWithPopup, getAdditionalUserInfo } from "firebase/auth"
const result = await signInWithPopup(auth, googleProvider);
// Pass the UserCredential
const { isNewUser } = getAdditionalUserInfo(result)
Related Topics
How to Remove the Top and Bottom Space on Textview of Android
Set Font for All Textviews in Activity
Android Spannablestring Set Background Behind Part of Text
Adt Blank Activity Created with Fragment Activity
Android Wifi How to Detect When Specific Wifi Connection Is Available
Whatsapp Like Collapsing Toolbar
Clear Text in Edittext When Entered
Android Google Maps API V2 Zoom to Current Location
Preventing/Catching "Illegalargumentexception: Parameter Must Be a Descendant of This View" Error
How to Use Device Default Theme for App
Android Studio Create Project Template for New Projects
Cannot Find Symbol Databindingcomponent on Android Studio 3.2 Canary 16 Kotlin Project
Android Beginner Difference Between Padding and Margin
Why Does Gradle Build My Module in Release Mode When the App Is in Debug
Android. Scrolling 2 Listviews Together
Android Activity Has Leaked Window Com.Android.Internal.Policy.Impl.Phonewindow$Decorview Issue
Changing Text Color of Menu Item in Navigation Drawer
Error Java.Lang.Runtimeexception: Stub! in Android with Fitnesse Testing