I need to check if the user is signing in for the first time, and initialize their account with extra properties (points, membership, etc) if true.
May user change his device and wants login again on another device.
I'm using google sign-in method. I tried something like this.
if(FirebaseAuth.getInstance().getCurrentUser() != null){
Toast.makeText(Anamain.this, "Welcome again xyz", Toast.LENGTH_SHORT).show();
}
I sign-in with new account, so first time in this app, but it's show "Welcome again xyz" message anyway.
How can I detect if user exist on database before?
Full code
package com.mertg.testsignin;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.FirebaseDatabase;
public class Anamain extends AppCompatActivity {
private String TAG = "Anamain";
private SignInButton signIn;
GoogleSignInClient mGoogleSignInClient;
private int RC_SIGN_IN = 1;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_anamain);
signIn = (SignInButton)findViewById(R.id.googleBtn);
mAuth = FirebaseAuth.getInstance();
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signIn();
}
});
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d("TAG", "signInWithCredential:success" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
/* if (!task.isSuccessful()){
Log.d("TAG", "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
}*/
if(FirebaseAuth.getInstance().getCurrentUser() != null){
Toast.makeText(Anamain.this, "Welcome again xyz", Toast.LENGTH_SHORT).show();
}
else {
//Log.w("TAG", "signInWithCredential:failure", task.getException());
// Toast.makeText(Anamain.this, "Basaramadim", Toast.LENGTH_SHORT).show();
//updateUI(null);
Toast.makeText(Anamain.this, "Register Successful", Toast.LENGTH_SHORT).show();
FirebaseUser user = mAuth.getCurrentUser();
//updateUI(user);
}
}
});
}
private void updateUI(FirebaseUser user) {
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if(acct != null) {
String personName = acct.getDisplayName();
Toast.makeText(this, "Sen Girdin" + personName, Toast.LENGTH_SHORT).show();
}
}
}
UPDATE
I get error: ';' expected for this line
mAuth.signInWithCredential(credential)
This is how ı replaced.
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d("TAG", "signInWithCredential:success" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(authCredential).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!");
}
}
});
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With