I'm implementing google sign-in using firebase, when I'm getting instance of firebaseauth class then its throws an exception,
java.lang.NoSuchMethodError
but my code is copied as it is from documentation(https://firebase.google.com/docs/auth/android/google-signin). Please help.
code:
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity_Firebase";
private static final int RC_SIGN_IN = 9001;
private FirebaseAuth mAuth;
private GoogleSignInClient mGoogleSignInClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance(); //this line is shown as error
//finding button and setting click listener
findViewById(R.id.signInButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
}
void setupGoogleSignIn(){
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
setupGoogleSignIn();
Intent signInIntent = mGoogleSignInClient.getSignInIntent(); //getting signIn intent from googleclient
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);
Log.d(TAG, "firebaseAuthWithGoogle: " + account.getIdToken());
firebaseAuthWithGoogle(account.getIdToken());
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
}
}
}
private void firebaseAuthWithGoogle(String idToken) {
Log.d(TAG, "firebaseAuthWithGoogle: called");
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
}
}
});
}
}
The complete Logcat
Process: com.recipeapp.marathi, PID: 13369
java.lang.NoSuchMethodError: No virtual method setTokenProvider(Lcom/google/firebase/internal/InternalTokenProvider;)V in class Lcom/google/firebase/FirebaseApp; or its super classes (declaration of 'com.google.firebase.FirebaseApp' appears in /data/app/com.recipeapp.marathi-3W2YRoeaSMJdnEELQ9KFbw==/base.apk)
at com.google.firebase.auth.FirebaseAuth.zza(Unknown Source:22)
at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source:4)
at com.recipeapp.marathi.activities.LoginActivity.onCreate(LoginActivity.java:37)
at android.app.Activity.performCreate(Activity.java:7964)
at android.app.Activity.performCreate(Activity.java:7953)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3472)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3636)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2222)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:228)
at android.app.ActivityThread.main(ActivityThread.java:7782)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)
dependencies:
//auth firebase
implementation platform('com.google.firebase:firebase-bom:26.7.0')
implementation "com.google.firebase:firebase-database:$firebase_google_version"
implementation "com.google.firebase:firebase-auth:$firebase_google_version"
implementation "com.google.android.gms:play-services-auth:$firebase_google_version"
implementation "com.google.firebase:firebase-ads:$firebase_google_version"
implementation 'com.firebaseui:firebase-ui-database:7.1.1'
pls help me fix this.
Related
I have LoginActivity with Email/password login, facebook, google authentication. It works separately but if I create account with google, I can't login with facebook.
Login activity code:
public class LoginActivity extends AppCompatActivity {
private Button mLogin,mRegister;
private int RC_SIGN_IN =0;
private EditText mEmail, mPassword;
public FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthStateListener;
CallbackManager callbackManager;
private LoginButton loginButton;
private static final String EMAIL = "email";
private TextView facebookRegister;
private SignInButton googleSignIn;
GoogleSignInClient mGoogleSignInClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Intent intent = new Intent(LoginActivity.this, LoginTest.class);
startActivity(intent);
//FACEBOOK
mAuth = FirebaseAuth.getInstance();
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(getApplication());
callbackManager = CallbackManager.Factory.create();
// 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();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
googleSignIn = findViewById(R.id.sign_in_button);
googleSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
// ...
}
}
});
firebaseAuthStateListener= new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user !=null){
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
return;
}
}
};
loginButton = findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList(EMAIL));
mLogin = (Button) findViewById(R.id.login);
mEmail = (EditText) findViewById(R.id.email);
mPassword=(EditText) findViewById(R.id.password);
mRegister=(Button)findViewById(R.id.register);
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
handleFacebookToken(loginResult.getAccessToken());
//fill database
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logInEmailPassword();
}
});
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegistrationActivity.class);
startActivity(intent);
finish();
return;
}
});
}
#Override
protected void onStart() {
super.onStart();
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
mAuth.addAuthStateListener(firebaseAuthStateListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthStateListener);
}
private void logInEmailPassword() {
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
if(email.isEmpty()){
Toast.makeText(LoginActivity.this, "Wrong email", Toast.LENGTH_SHORT).show();
mEmail.setError("Enter email!");
};
if(password.isEmpty()){
mPassword.setError("Enter password!");
Toast.makeText(LoginActivity.this, "Wrong password", Toast.LENGTH_SHORT).show();
}
if(!email.isEmpty() && !password.isEmpty()){
AuthCredential credential = EmailAuthProvider.getCredential(email, password);
linkWithCredential(credential);
}
}
private void handleFacebookToken(AccessToken token) {
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
linkWithCredential(credential);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
FirebaseGoogleAuth(account);
// Signed in successfully, show authenticated UI.
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w("myLog", "signInResult:failed code=" + e.getStatusCode());;
}
}
private void FirebaseGoogleAuth(GoogleSignInAccount account) {
AuthCredential authCredential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
linkWithCredential(authCredential);
}
private void linkWithCredential(AuthCredential credential){
mAuth = FirebaseAuth.getInstance()
//mAuth.getCurrentUser().linkWithCredential(credential)
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("myLog", "linkWithCredential:success");
FirebaseUser user = task.getResult().getUser();
updateUI(user);
} else {
Log.w("myLog", "linkWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
LoginManager.getInstance().logOut();
updateUI(null);
}
// ...
}
});
}
}
I've followed https://firebase.google.com/docs/auth/android/account-linking?authuser=0 tutorial but I stuck at linkWithCredential.
Can you help me fix that issue? Thanks
The problem if that user exists in Firebase Authentication already and is assigned to GoogleAuth i cant login with Facebook.
It works vice versa, if facebook user exists in firebase and i login with google it overrides that user.
Register ---- logout ---- login
Google --->>>>>>>>>>>>>>>>Facebook >>>>dont work
Facebook--->>>>>>>>>>>>>>>Google >>>>> works
I have a LoginActivity where user signs in to my app via Firebase (sign in with Google). How to access and update the signed-in user's details in other activity. Also how to sign out the user in the next or other activity.
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
private SignInButton signInButton;
private GoogleSignInClient googleSignInClient;
private String TAG = "Login Activity";
private FirebaseAuth auth;
private int RC_SIGN_IN = 1;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
signInButton = findViewById(R.id.btnSignInGoogle);
auth = FirebaseAuth.getInstance();
sp = getSharedPreferences("login", MODE_PRIVATE);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
if (sp.getBoolean("logged",false)){
gotoMainActivity();
}else {
googleSignInClient = GoogleSignIn.getClient(this, gso);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signin();
}
});
}
}
private void signin() {
Intent signInIntent = googleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN){
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask){
try {
GoogleSignInAccount acc = completedTask.getResult(ApiException.class);
//Signed In Successfully
FirebaseGoogleAuth(acc);
} catch (ApiException e) {
e.printStackTrace();
//Sign In Failed
FirebaseGoogleAuth(null);
}
}
private void FirebaseGoogleAuth(final GoogleSignInAccount acct) { //To handle firebase google authentication
AuthCredential authCredential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
auth.signInWithCredential(authCredential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) { //checking authentication credential and checking successful or not
if (task.isSuccessful()) {
// Success
FirebaseUser user = auth.getCurrentUser();
updateUI(user);
} else {
// Fail
updateUI(null);
}
}
});
}
private void updateUI(FirebaseUser fuser) {
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if (account != null){
gotoMainActivity();
sp.edit().putBoolean("logged", true).apply();
}
}
private void gotoMainActivity() {
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
}}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private FirebaseUser user;
Button btnSignOut;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSignOut = findViewById(R.id.btnSignInGoogle);
textView = findViewById(R.id.textView);
user = FirebaseAuth.getInstance().getCurrentUser();
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user.signout();
}
});
}}
I want to sign out the user in MainActivity. And I want to access and update all the details about the user in MainActivity and other activities in the future.
I want to sign out the user in MainActivity.
You can not call signout() on a FirebaseUser object, you should call it on a FirebaseAuth object like this:
FirebaseAuth.getInstance().signout();
And I want to access and update all the details about the user in MainActivityand other activities in the future.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
if(user != null) {
Map<String, Object> updates = new HashMap<>();
updates.put("fieldName", "fieldData");
FirebaseFirestore.getInstance().collection("users").document(uid).update(updates);
}
In this way you can update a field name of type String in user document in Cloud Firestore.
The problem is that when I run this code with authorization in Google, it immediately crashes:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
//mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
} else {
}
}
};
et_email = (EditText) findViewById(R.id.et_email);
et_password = (EditText) findViewById(R.id.et_password);
mDetailTextView = (TextView) findViewById(R.id.mDetailTextView);
mStatusTextView = (TextView) findViewById(R.id.mStatusTextView);
findViewById(R.id.BVoiti).setOnClickListener(this);
findViewById(R.id.change_email).setOnClickListener(this);
findViewById(R.id.change_password).setOnClickListener(this);
findViewById(R.id.btn_vk).setOnClickListener(this);
findViewById(R.id.BReg).setOnClickListener(this);
}
#Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.btn_google) {
signIn();
}
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleSignInClient);
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);
// ...
}
}
}
public void signing(String email, String password){
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Авторизация успешна", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Авторизация провалена", Toast.LENGTH_SHORT).show();
}
}
});
}
public void registration (String email, String password){
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Регистрация успешна, теперь войдите", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(MainActivity.this, "Регистрация провалена", Toast.LENGTH_SHORT).show();
}
}
});
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + 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()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(MainActivity.this, "Authentication Failed.", Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
}
private void updateUI(FirebaseUser user) {
if (user != null) {
mStatusTextView.setText( user.getEmail());
mDetailTextView.setText( user.getUid());
findViewById(R.id.btn_google).setVisibility(View.GONE);
findViewById(R.id.btn_vk).setVisibility(View.VISIBLE);
} else {
mStatusTextView.setText("Вышел");
mDetailTextView.setText(null);
findViewById(R.id.btn_google).setVisibility(View.VISIBLE);
findViewById(R.id.btn_vk).setVisibility(View.GONE);
}
}
}
But the error in the logs:
2019-06-22 17:55:42.652 29327-23222/? E/AudioSource: Stop listening is
called on already closed AudioSource 2019-06-22 17:55:43.240
2093-2616/? E/TouchFilter: setTouchFilter LOG Enable prameter: 0
2019-06-22 17:55:43.554 31234-31234/com.anntoxa.foodforyou
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.anntoxa.foodforyou, PID: 31234
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.anntoxa.foodforyou/com.anntoxa.foodforyou.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2805)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2883)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1613)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference
at com.anntoxa.foodforyou.MainActivity.updateUI(MainActivity.java:176)
at com.anntoxa.foodforyou.MainActivity.onCreate(MainActivity.java:51)
at android.app.Activity.performCreate(Activity.java:7023)
at android.app.Activity.performCreate(Activity.java:7014)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2883)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1613)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)
2019-06-22 17:55:43.564 2093-2156/? E/ActivityManager_tangan: app
crash,kill it 2019-06-22 17:55:43.569 384-384/? E/lowmemorykiller:
Error writing /proc/31234/oom_score_adj; errno=22
You should move this block:
mDetailTextView = (TextView) findViewById(R.id.mDetailTextView);
mStatusTextView = (TextView) findViewById(R.id.mStatusTextView);
before calling updateUI in onCreate
I am using Firebase Auth. I am trying to sing in a user with Google Account, using the signInWithCredential method. The credential from Google are ok, but when I try to sign in the user with firebase i get an error:
login error: signInWithCredential:failure com.google.firebase.auth.FirebaseAuthInvalidUserException: There is no user record corresponding to this identifier. The user may have been deleted. at com.google.android.gms.internal.zzdjy.zzak(Unknown Source:84) at com.google.android.gms.internal.zzdja.zza(Unknown Source:12)com.google.android.gms.internal.zzdki.zzal(Unknown Source:11)com.google.android.gms.internal.zzdkk.onFailure(Unknown Source:35)com.google.android.gms.internal.zzdka.onTransact(Unknown Source:79)android.os.Binder.execTransact(Binder.java:674)
I would understand the error if i would be singing in the user with email and password provider not with Google credentials.
And this error is from a new project so no users were ever authenticated.
I allready tried changing signingConfigs in gradle and changing the sha1 keys in firebase console. Deleted the project multiple times and i cant seem to get it to work.
It's weird because i remember that i had no problems in the past with this.
Help if you cant. Thank you.
Source:
private static final int RC_SIGN_IN = 1;
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
findViewById(R.id.sign).setOnClickListener(this);
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
Log.d("login", "googleSignInRsult:error");
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
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("login", "signInWithCredential:success");
} else {
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
Log.w("login", "signInWithCredential:failure", task.getException());
}
}
});
}
Reinstalled Android Studio and everything is working now.
I'm finished with android app. Used firebase, admob. Has 31 activities. But when user installs the app for first time, the launch time is approximately 18 seconds which is too high. After first time launching, signup activity is there. But if we relaunch the app then it launches in 2 seconds. Why there is very high launch time? How can I reduce it? Below is my Sign up activity code. Using android studio 2.2
public class MainActivity extends AppCompatActivity {
private AdView mAdView;
private SignInButton mGoogleBtn;
private static final int RC_SIGN_IN=1;
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
private static final String TAG="MAIN_ACTIVITY";
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth=FirebaseAuth.getInstance();
mAuthListener=new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser()!=null){
startActivity(new Intent(MainActivity.this,Home.class));
}
}
};
mGoogleBtn=(SignInButton)findViewById(R.id.view);
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient=new GoogleApiClient.Builder(getApplicationContext())
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(MainActivity.this,"Login via Google Failed! Press Skip",Toast.LENGTH_LONG).show();
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API,gso)
.build();
mGoogleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#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) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed. Press Skip.",
Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this,"Login Successful! Welcome to Unipune Buddy!",Toast.LENGTH_LONG).show();
}
// ...
}
});
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
public void mainscreen(View view){
Intent intent0=new Intent(this,Home.class);
Toast.makeText(MainActivity.this,"Signed in Successfully!",Toast.LENGTH_LONG).show();
startActivity(intent0);
}
}
I too had this issue, what i had done was disabling instant run in the project settings, and rebuilding the project, You can also use Cold start for engaging the user for the first time.