I want to record the account data to firebase realltime-database when I logged in with Google Account/facebook account in app but I couldn't expect my goal because whiIe I'm starting to log in application and the storing processing, the application is force closed.
This was code I've tried
LoginActivity.java
package id.co.dolansemarang.loginfirebaseds;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
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.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
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.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DatabaseReference;
import id.co.dolansemarang.loginfirebaseds.model.User;
import id.co.dolansemarang.loginfirebaseds.model.UsersProvider;
public class LoginActivity extends BaseActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "Login User";
private static final int RC_SIGN_IN = 1234;
CallbackManager callbackManager;
GoogleSignInClient googleSignInClient;
GoogleApiClient mGoogleApiClient;
LoginButton loginButton;
Button btnLogin;
LinearLayout btnGoogleSignIn, btnFacebookSignIn;
EditText edtEmailLogin, edtPasswordLogin;
TextView tvResetPass, tvRegisterLink;
FirebaseAuth firebaseAuthLogin;
FirebaseAuth.AuthStateListener authStateListener;
// DatabaseReference userRefLogin;
FirebaseUser curUser;
DatabaseReference providerLoginRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnLogin = findViewById(R.id.btn_login);
edtEmailLogin = findViewById(R.id.edt_email_login);
edtPasswordLogin = findViewById(R.id.edt_password_login);
tvResetPass = findViewById(R.id.tv_reset_pass);
tvRegisterLink = findViewById(R.id.tv_register_link);
btnGoogleSignIn = findViewById(R.id.btn_sign_in_with_google);
btnFacebookSignIn = findViewById(R.id.btn_sign_in_with_facebook);
loginButton = findViewById(R.id.login_button);
firebaseAuthLogin = FirebaseAuth.getInstance();
// authStateListener = new FirebaseAuth.AuthStateListener() {
// #Override
// public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
// if (curUser != null) {
// Log.d(TAG, "onAuthStateChanged: Sign In");
// } else {
// Log.d(TAG, "onAuthStateChanged:signed_out");
// }
// }
// };
//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(LoginActivity.this)
.enableAutoManage(LoginActivity.this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
googleSignInClient = GoogleSignIn.getClient(this, gso);
//facebook Sign In
callbackManager = CallbackManager.Factory.create();
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook: onSuccess Login" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook: onCancel");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook: onError", error);
}
});
btnFacebookSignIn.setOnClickListener(this);
btnLogin.setOnClickListener(this);
tvResetPass.setOnClickListener(this);
btnGoogleSignIn.setOnClickListener(this);
tvRegisterLink.setOnClickListener(this);
}
private void handleFacebookAccessToken(AccessToken accessToken) {
Log.d(TAG, "handleFacebookAccessToken : " + accessToken);
showProgressDialog();
AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
firebaseAuthLogin.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "your account has been success to register");
FirebaseUser user = firebaseAuthLogin.getCurrentUser();
// updateUI(user);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
Toast.makeText(LoginActivity.this, "Welcome " + user.getEmail() + "", Toast.LENGTH_LONG).show();
finish();
} else {
Log.w(TAG, "please, try again", task.getException());
Toast.makeText(LoginActivity.this, "Gagal Login, silakan coba lagi", Toast.LENGTH_LONG).show();
// updateUI(null);
}
hideProgressDialog();
}
});
}
#Override
protected void onStart() {
super.onStart();
// cek apakah pengguna sudah pernah masuk sehingga ada update UI disini
if(authStateListener!= null){
FirebaseUser currentUser = firebaseAuthLogin.getCurrentUser();
updateUI(currentUser);
authStateListener.onAuthStateChanged(firebaseAuthLogin);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
// GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
// handleSignInResult(result);
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
loginWithGoogle(account);
} catch (ApiException e) {
Log.w(TAG, "Google Sign I Failed", e);
updateUI(curUser);
}
}
}
private void loginWithGoogle(GoogleSignInAccount account) {
showProgressDialog();
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
firebaseAuthLogin.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
String nama =FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
String providerID =FirebaseAuth.getInstance().getCurrentUser().getProviderId();
UsersProvider users = new UsersProvider (uid,nama,email,providerID);
providerLoginRef.child("UsersProviders").child(uid).setValue(users).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
updateUI(curUser);
}
});
} else {
Log.w(TAG, "please, try again", task.getException());
Toast.makeText(LoginActivity.this, "Gagal Login, silakan coba lagi", Toast.LENGTH_LONG).show();
}
hideProgressDialog();
}
});
}
private void loginUserWithEmail(String email, String password) {
Log.d(TAG, "signIn:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
firebaseAuthLogin.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "your account has been success to register");
FirebaseUser user = firebaseAuthLogin.getCurrentUser();
if (user.isEmailVerified()) {
updateUI(user);
} else {
Toast.makeText(LoginActivity.this, "Silakan cek inbox untuk verifikasi", Toast.LENGTH_LONG).show();
}
} else {
Log.w(TAG, "please, try again", task.getException());
Toast.makeText(LoginActivity.this, "Gagal Login, silakan coba lagi", Toast.LENGTH_LONG).show();
// updateUI(null);
}
hideProgressDialog();
}
});
}
private void updateUI(FirebaseUser user) {
hideProgressDialog();
if (user != null) {
user.getDisplayName();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
Toast.makeText(this, "Welcome " + user.getEmail() + "", Toast.LENGTH_LONG).show();
finish();
}
}
private boolean validateForm() {
boolean valid = true;
String email = edtEmailLogin.getText().toString();
String password = edtPasswordLogin.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Harap isi email kembali", Toast.LENGTH_LONG).show();
valid = false;
} else {
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Harap isi password kembali", Toast.LENGTH_LONG).show();
valid = false;
} else {
if (password.length() <= 6) {
Toast.makeText(getApplicationContext(), "password contained minimum 6 character", Toast.LENGTH_LONG).show();
valid = false;
}
}
}
return valid;
}
#Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.btn_login) {
loginUserWithEmail(edtEmailLogin.getText().toString(), edtPasswordLogin.getText().toString());
} else if (i == R.id.tv_reset_pass) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
finish();
} else if (i == R.id.btn_sign_in_with_google) {
signInGoogle();
} else if (i == R.id.tv_register_link) {
gotoRegister();
} else if (i == R.id.btn_sign_in_with_facebook) {
loginButton.performClick();
}
}
private void gotoRegister() {
startActivity(new Intent(this, RegisterActivity.class));
finish();
}
private void signInGoogle() {
Intent signIntent = googleSignInClient.getSignInIntent();
startActivityForResult(signIntent, RC_SIGN_IN);
}
#Override
protected void onStop() {
super.onStop();
if (authStateListener != null) {
firebaseAuthLogin.removeAuthStateListener(authStateListener);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
I expect I can store but there is opposite because the logcat show the error like this
2019-05-04 20:55:13.471 16495-16495/id.co.dolansemarang.loginfirebaseds E/AndroidRuntime: FATAL EXCEPTION: main
Process: id.co.dolansemarang.loginfirebaseds, PID: 16495
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
at id.co.dolansemarang.loginfirebaseds.LoginActivity$3.onComplete(LoginActivity.java:203)
at com.google.android.gms.tasks.zzj.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
I would like you to help me, please. Thanks before
To solve this, please change the following line of code:
DatabaseReference providerLoginRef;
to
DatabaseReference providerLoginRef = FirebaseDatabase.getInstance().getReference();
So you got that error because your providerLoginRef object was never initialized.
Related
My app uses firebase and it needs to send a verification email to the user after registration before they can login. In my code, the app fails to send the verification email and I found out that the user is always null (while debugging) in line 86/88 of my code. any help would be greaty appreciated.
I've tried retracing my steps back but I couldn't get where i nicked an artery
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import static android.text.TextUtils.isEmpty;
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuthSetUp();
//widgets
TextView mSignUp = (TextView) findViewById(R.id.sign_up_txt);
TextView forgotPassword = (TextView) findViewById(R.id.forgot_password_txt);
Button mSignIn = (Button) findViewById(R.id.sign_in_btn);
final EditText mEmailSignIn = (EditText) findViewById(R.id.sign_in_email);
final EditText mPasswordSignIn = (EditText) findViewById(R.id.sign_in_password);
mSignUp.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
startActivity(intent);
}
}));
//sign in process
mSignIn.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isEmpty(mEmailSignIn.getText().toString()) && !isEmpty(mPasswordSignIn.getText().toString())) {
//showProgressBar();
FirebaseAuth.getInstance().signInWithEmailAndPassword(mEmailSignIn.getText().toString(), mPasswordSignIn.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//hideProgressBar();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, " Authentication Failed!!!", Toast.LENGTH_LONG).show();
//hideProgressBar();
}
});
} else {
Toast.makeText(LoginActivity.this, "Please, Fill All Fields", Toast.LENGTH_LONG).show();
}
}
}));
}
//Setting up Firebase
private void firebaseAuthSetUp() {
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
Log.d("TAG", "CurrentUser: " + user);
if (user != null) {
if(user.isEmailVerified()){
Log.d("TAG", "onAuthStateChanged: signed in: " + user.getEmail());
Toast.makeText(LoginActivity.this, "signed in " + user.getUid(), Toast.LENGTH_LONG).show();
} else{
Toast.makeText(LoginActivity.this, "Please Check Your Email Inbox for Verification Link " + user.getUid(), Toast.LENGTH_LONG).show();
FirebaseAuth.getInstance().signOut();
}
} else {
Toast.makeText(LoginActivity.this, "failed to sign in", Toast.LENGTH_LONG).show();
}
}
};
}
#Override
protected void onStart() {
super.onStart();
FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if (mAuthListener != null) {
FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);
}
}
/*public void showProgressBar(){
mProgressBar.setVisibility(View.VISIBLE);
}
public void hideProgressBar(){
if (mProgressBar.getVisibility() == View.VISIBLE){
mProgressBar.setVisibility(View.INVISIBLE);
}
}*/
}```
Thanks a lot #Praveen and #Alex... figured it out, I made a mistake of signing out the user in the else statement [of the if(user.isEmailVerified()) block in the firebaseAuthSetup() method]. probably wouldn't have gotten it if I didn't retrace from the onComplete()
I have a system that saves createUserWithEmailAndPassword data to a realtime database and to the authentication database. But after making a similar system using google sign in instead nothing will save to the Authentication database, the app just crashes with my current code.
ive tried using Log.e, ive tried debugging the app and also tried to decode the code...
heres some code:
package com.brandshopping.brandshopping;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
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.auth.api.Auth;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
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.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
public class LoginOrSignupActivity extends AppCompatActivity {
private Button LoginBtn, RegisterWithEmailBtn, RegisterWithGoogleBtn;
private String Tag;
private ProgressDialog LoadingBar;
private FirebaseDatabase firebasedatabase = FirebaseDatabase.getInstance();
private DatabaseReference database = firebasedatabase.getReference();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_or_signup);
LoadinGUI();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso); //Create Google sign in object
LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginOrSignupActivity.this, LogInActivity.class));
}
});
RegisterWithEmailBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginOrSignupActivity.this, RegisterActivity.class));
}
});
RegisterWithGoogleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.Register_WithGoogle_btn:
signIn();
break;
}
}
});
}
private void signIn() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(LoginOrSignupActivity.this, gso); //Create Google sign in object
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
int RC_SIGN_IN = 100;
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int RC_SIGN_IN = 100;
// 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 handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
Toast.makeText(this, "Register/signin successful", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginOrSignupActivity.this, AccountInfoActivity.class));
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Toast.makeText(this, "Log in failed", Toast.LENGTH_SHORT).show();
Log.e(Tag, "error: ");
startActivity(new Intent(LoginOrSignupActivity.this, AccountInfoActivity.class));
}
}
void SaveToDataBase() {
database.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
GoogleSignInAccount Guser = GoogleSignIn.getLastSignedInAccount(LoginOrSignupActivity.this);
String EmailWithEtheraRemoved = Guser.getEmail().replace(".", " ");
if (!(dataSnapshot.child("Users").child(EmailWithEtheraRemoved).exists())) {
LoadingBar.setMessage("Please wait while we load the credentialls in");
LoadingBar.setTitle("Register");
LoadingBar.setCanceledOnTouchOutside(false);
LoadingBar.show();
HashMap<String, Object> Userdatamap = new HashMap<>();
Userdatamap
.put("Email", Guser.getEmail());
Userdatamap
.put("Phone number", "Google intigrated sign in does not allow phone number requesting... This will be fixed in later patches");
Userdatamap
.put("Name", Guser.getGivenName() + Guser.getFamilyName());
if (Guser != null) {
Userdatamap
.put("Created with", "Intigrated Google sign in");
}
database
.child("Users")
.child(EmailWithEtheraRemoved)
.updateChildren(Userdatamap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
LoadingBar.dismiss();
Toast.makeText(LoginOrSignupActivity.this, "Database save successful", Toast.LENGTH_SHORT).show();
Log.e("SignUpError :", task
.getException()
.getMessage());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginOrSignupActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
Log.e(Tag, "error: ");
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d("authenticate", "firebaseAuthWithGoogle:" + acct.getId());
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
final GoogleSignInAccount Guser = GoogleSignIn.getLastSignedInAccount(LoginOrSignupActivity.this);
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("message","signInWithCredential:success");
Log.d("user id", Guser.getId());
startActivity(new
Intent(LoginOrSignupActivity.this,MainActivity.class));
} else {
// If sign in fails, display a message to the user.
Log.w("message","signInWithCredential:failure", task.getException());
}
}
});
}
void LoadinGUI() {
LoadingBar = new ProgressDialog(LoginOrSignupActivity.this);
LoginBtn = (Button) findViewById(R.id.Login_btn);
RegisterWithEmailBtn = (Button) findViewById(R.id.Register_WithEmail_btn);
RegisterWithGoogleBtn = (Button) findViewById(R.id.Register_WithGoogle_btn);
}
}
I am expecting the app to save info to the authentication database.
this is the debug file:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.brandshopping.brandshopping, PID: 30495
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=Intent { (has extras) }} to activity {com.brandshopping.brandshopping/com.brandshopping.brandshopping.LoginOrSignupActivity}: java.lang.IllegalArgumentException: Must specify an idToken or an accessToken.
at android.app.ActivityThread.deliverResults(ActivityThread.java:4936)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4978)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2123)
at android.os.Handler.dispatchMessage(Handler.java:109)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:7470)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958)
Caused by: java.lang.IllegalArgumentException: Must specify an idToken or an accessToken.
at com.google.firebase.auth.GoogleAuthCredential.<init>(Unknown Source:3)
at com.google.firebase.auth.GoogleAuthProvider.getCredential(Unknown Source:2)
at com.brandshopping.brandshopping.LoginOrSignupActivity.firebaseAuthWithGoogle(LoginOrSignupActivity.java:213)
at com.brandshopping.brandshopping.LoginOrSignupActivity.handleSignInResult(LoginOrSignupActivity.java:127)
at com.brandshopping.brandshopping.LoginOrSignupActivity.onActivityResult(LoginOrSignupActivity.java:116)
at android.app.Activity.dispatchActivityResult(Activity.java:7775)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4929)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4978)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2123)
at android.os.Handler.dispatchMessage(Handler.java:109)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:7470)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958)
I've logined google account on the application but when I logout of the system, the application force closed. In another, couldn't show google account chooser when I started to login the application again
This was the code I've tried and the problem is null object reference on methode GoogleSignIn Client and I couldn't find method revokeaccess cause it was unavailable.
Login Activity.java
package id.co.dolansemarang.loginfirebaseds;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
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.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
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;
public class LoginActivity extends BaseActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "Login User";
private static final int RC_SIGN_IN = 1234;
GoogleSignInClient googleSignInClient;
GoogleApiClient mGoogleApiClient;
Button btnLogin;
LinearLayout btnGoogleSignIn;
EditText edtEmailLogin, edtPasswordLogin;
TextView tvResetPass;
FirebaseAuth firebaseAuthLogin;
// DatabaseReference userRefLogin;
FirebaseUser curUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnLogin = findViewById(R.id.btn_login);
edtEmailLogin = findViewById(R.id.edt_email_login);
edtPasswordLogin = findViewById(R.id.edt_password_login);
tvResetPass = findViewById(R.id.tv_reset_pass);
btnGoogleSignIn = findViewById(R.id.btn_sign_in_with_google);
//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(LoginActivity.this)
.enableAutoManage(LoginActivity.this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
googleSignInClient = GoogleSignIn.getClient(this, gso);
firebaseAuthLogin = FirebaseAuth.getInstance();
btnLogin.setOnClickListener(this);
tvResetPass.setOnClickListener(this);
btnGoogleSignIn.setOnClickListener(this);
updateUI(curUser);
}
#Override
protected void onStart() {
super.onStart();
// cek apakah pengguna sudah pernah masuk sehingga ada update UI disini
FirebaseUser currentUser = firebaseAuthLogin.getCurrentUser();
updateUI(currentUser);
}
#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);
try{
GoogleSignInAccount account = task.getResult(ApiException.class);
loginWithGoogle(account);
}
catch (ApiException e){
Log.w(TAG, "Google Sign I Failed", e);
updateUI(curUser);
}
}
}
private void loginWithGoogle(GoogleSignInAccount account) {
Log.d(TAG, "FirebaseAuthWithGoogle" +account.getId());
showProgressDialog();
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
firebaseAuthLogin.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "your account has been success to register");
FirebaseUser user = firebaseAuthLogin.getCurrentUser();
updateUI(user);
} else {
Log.w(TAG, "please, try again", task.getException());
Toast.makeText(LoginActivity.this, "Gagal Login, silakan coba lagi", Toast.LENGTH_LONG).show();
// updateUI(null);
}
hideProgressDialog();
}
});
}
private void loginUserWithFirebase(String email, String password) {
Log.d(TAG, "signIn:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
firebaseAuthLogin.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "your account has been success to register");
FirebaseUser user = firebaseAuthLogin.getCurrentUser();
updateUI(user);
} else {
Log.w(TAG, "please, try again", task.getException());
Toast.makeText(LoginActivity.this, "Gagal Login, silakan coba lagi", Toast.LENGTH_LONG).show();
// updateUI(null);
}
hideProgressDialog();
}
});
}
private void updateUI(FirebaseUser user) {
hideProgressDialog();
if (user != null && user.isEmailVerified()) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
Toast.makeText(this, "Welcome " + user.getEmail() + "", Toast.LENGTH_LONG).show();
finish();
} else if (user != null && !user.isEmailVerified()) {
Toast.makeText(getApplicationContext(), "Please verify your Email, first", Toast.LENGTH_SHORT).show();
} else {
Log.d(TAG, "Selamat datang");
}
}
private boolean validateForm() {
boolean valid = true;
String email = edtEmailLogin.getText().toString();
String password = edtPasswordLogin.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Harap isi email kembali", Toast.LENGTH_LONG).show();
valid = false;
} else {
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Harap isi password kembali", Toast.LENGTH_LONG).show();
valid = false;
} else {
if (password.length() <= 6) {
Toast.makeText(getApplicationContext(), "password contained minimum 6 character", Toast.LENGTH_LONG).show();
valid = false;
}
}
}
return valid;
}
#Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.btn_login) {
loginUserWithFirebase(edtEmailLogin.getText().toString(), edtPasswordLogin.getText().toString());
} else if (i == R.id.tv_reset_pass) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
finish();
} else if(i == R.id.btn_sign_in_with_google){
signInGoogle();
}
}
private void signInGoogle() {
Intent signIntent = googleSignInClient.getSignInIntent();
startActivityForResult(signIntent, RC_SIGN_IN);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Main Activity.java
package id.co.dolansemarang.loginfirebaseds;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
FirebaseAuth firebaseAuthMain;
FirebaseUser user;
Button btnKeluar;
GoogleSignInClient googleSignInClient;
GoogleApiClient googleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnKeluar = findViewById(R.id.btn_sign_out);
firebaseAuthMain = FirebaseAuth.getInstance();
btnKeluar.setOnClickListener(this);
user = firebaseAuthMain.getCurrentUser();
}
#Override
public void onClick(View v) {
int i = v.getId();
if(i == R.id.btn_sign_out){
// firebaseAuthMain.signOut();
// googleSignInClient.signOut().addOnCompleteListener(this, new OnCompleteListener<Void>() {
// #Override
// public void onComplete(#NonNull Task<Void> task) {
// updateUI(null);
// }
// });
// updateUI(user);
signOutApp();
signOutGoogle();
}
}
private void signOutGoogle() {
googleSignInClient.signOut().addOnCompleteListener(this,
new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
updateUI(null);
}
});
}
private void signOutApp() {
firebaseAuthMain.signOut();
updateUI(user);
}
private void updateUI(FirebaseUser user) {
if(user != null){
startActivity(new Intent(MainActivity.this, LoginActivity.class));
Toast.makeText(this,"Thanks for visiting",Toast.LENGTH_LONG).show();
finish();
}
}
}
I expected when I login with either email or google account and then Logout without conflict. So, How should I do?
Following the document here google-signin
Just only FirebaseAuth.getInstance().signOut(); to logout
So you might have to call signOutApp() function only.
This is my RegistrationActivity.java where I want user to choose image while registering time. Everything works fine except image updation! When I register a new user and when I click in image, it opens my image gallery, I choose any image, and it back to register activity but it won't update. Also I'm unable to register because that image is not uploading successfully and I sat (if
imagepath == null), so that's why toast error is coming that fill all the details.
NOTE:
1. I tried multiple images, same issue, also I resize some images and tried.
2.There is no error in logcat.
3.Default image is showing perfectly when we first time try to register that time I sat android logo which is default.
4.I can't register without selecting any image because imagepath == null and I exactly want that user should not register if he/she not upload the image.
5.I sat imageview size :
android:layout_width="150dp"
android:layout_height="150dp"
in my activity_registration.xml file. Is there cause any problem?
package com.jimmytrivedi.loginapp;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
public class RegistrationActivity extends AppCompatActivity {
private EditText userName, userEmail, userPassword, userAge;
private Button SignUp;
private TextView userLogin;
private FirebaseAuth firebaseAuth;
private ImageView profile;
private FirebaseStorage firebaseStorage;
private static int PICK_IMAGE = 123;
String name, email, password, age;
Uri imagePath;
private StorageReference storageReference;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE && requestCode == RESULT_OK && data.getData() != null) {
imagePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagePath);
profile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setUpUIViews();
firebaseAuth = FirebaseAuth.getInstance();
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
SignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
//upload data to the database
String user_email = userEmail.getText().toString().trim();
String user_password = userPassword.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(user_email, user_password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
sendEmailVerification();
} else {
Toast.makeText(RegistrationActivity.this, "Registration failed!", Toast.LENGTH_SHORT)
.show();
}
}
});
}
}
});
userLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}
});
}
private void setUpUIViews() {
userName = findViewById(R.id.userName);
userEmail = findViewById(R.id.userEmail);
userPassword = findViewById(R.id.userPassword);
SignUp = findViewById(R.id.userRegister);
userLogin = findViewById(R.id.userLogin);
userAge = findViewById(R.id.userAge);
profile = findViewById(R.id.profile);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE);
}
});
}
private boolean validate() {
Boolean result = false;
name = userName.getText().toString();
email = userEmail.getText().toString();
password = userPassword.getText().toString();
age = userAge.getText().toString();
if (name.isEmpty() || password.isEmpty() || email.isEmpty() || age.isEmpty()
|| imagePath == null) {
Toast.makeText(this, "Please enter all the details", Toast.LENGTH_SHORT)
.show();
} else {
result = true;
}
return result;
}
private void sendEmailVerification() {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
sendUserData();
Toast.makeText(RegistrationActivity.this, "Successfully registered, Verification email has been sent",
Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
finish();
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
} else {
Toast.makeText(RegistrationActivity.this, "Verification email hasn't been sent",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void sendUserData() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myReference = firebaseDatabase.getReference(firebaseAuth.getUid());
StorageReference imageReference = storageReference.
child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
UploadTask uploadTask = imageReference.putFile(imagePath);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this, "Upload failed", Toast.LENGTH_SHORT)
.show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(RegistrationActivity.this, "Upload successful", Toast.LENGTH_SHORT)
.show();
}
});
UserProfile userProfile = new UserProfile(age, email, name);
myReference.setValue(userProfile);
}
}
Replace your sendUserData with this
private void sendUserData() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myReference = firebaseDatabase.getReference(firebaseAuth.getUid());
StorageReference imageReference = storageReference.
child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
imageReference.putFile(imagePath).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this, "Upload failed", Toast.LENGTH_SHORT)
.show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(RegistrationActivity.this, "Upload successful", Toast.LENGTH_SHORT)
.show();
}
});
UserProfile userProfile = new UserProfile(age, email, name);
myReference.setValue(userProfile);
}
I am trying to use the Google people API in order to get the personal user information like date of birth, age range, interests and so on..
But when I am trying to access it using the code below,
meProfile = service.people().get("people/me").setRequestMaskIncludeField("people.AgeRange").execute();
The code is returning null.
My "meProfile" object is always null.
I have even tried by setting flags
like
meProfile = service.people().get("people/me").setRequestMaskIncludeField("people.AgeRange").execute();
even then the result was same. I am getting the null value.
My complete code of the LoginActivity is as below
LOGINACTIVITY.java
import android.accounts.Account;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.people.v1.People;
import com.google.api.services.people.v1.model.Gender;
import com.google.api.services.people.v1.model.Person;
import com.google.firebase.FirebaseApp;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class LoginActivity extends AppCompatActivity implements
View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener
{
private static HttpTransport HTTP_TRANSPORT;
private static JsonFactory JSON_FACTORY;
private static final String TAG = "GoogleActivity";
private static final int RC_SIGN_IN = 9001;
private String email,name,fname;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private GoogleApiClient mGoogleApiClient;
Button signUpBtn,loginFireBaseBtn,loginGoogleBtn;
EditText loginEt,passwordEt;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
loginEt=(EditText)findViewById(R.id.emailLoginEt);
passwordEt=(EditText)findViewById(R.id.passwordLoginEt);
loginFireBaseBtn=(Button)findViewById(R.id.loginBtn);
signUpBtn= (Button)findViewById(R.id.signUpBtn);
findViewById(R.id.googleSignInButton).setOnClickListener(this);
loginFireBaseBtn.setOnClickListener(this);
signUpBtn.setOnClickListener(this);
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null)
{
// User is signed in
if (name!=null&&email!=null&&fname!=null)
{
Toast.makeText(getApplicationContext(),"GOOGLE: \n"+email+"\n"+name+"\n"+fname, Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), NonAdminACtivity.class);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
startActivity(intent);
finish();
}
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
}
else
{
// User is signed out
Toast.makeText(getApplicationContext(),"Signed out", Toast.LENGTH_LONG).show();
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
// [START config_signin]
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// [END config_signin]
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
public void showProgressBar()
{
progressDialog = new ProgressDialog(LoginActivity.this,
R.style.MyTheme);
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
progressDialog.setMessage("Haha Can't Hack...");
progressDialog.show();
}
public void cancelProgressBar()
{
progressDialog.dismiss();
}
#Override
public void onClick(View v)
{
if (v.getId()==R.id.loginBtn)
{
firebaseLogin();
}
if (v.getId()==R.id.googleSignInButton)
{
googleLogin();
}
if (v.getId()==R.id.signUpBtn)
{
firebaseSignUp();
}
}
private void googleLogin()
{
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);
// 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();
email = account.getEmail();
name = account.getDisplayName();
fname = account.getFamilyName();
getPersonalInfo(account);
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// [START_EXCLUDE]
Toast.makeText(this, "Google SIGN-IN Fialed!", Toast.LENGTH_SHORT).show();
// [END_EXCLUDE]
}
}
}
private void getPersonalInfo(final GoogleSignInAccount account)
{
/** Global instance of the HTTP transport. */
HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport();
/** Global instance of the JSON factory. */
JSON_FACTORY = JacksonFactory.getDefaultInstance();
new Thread(
new Runnable() {
#Override
public void run()
{
Collection<String> scopes = new ArrayList<>(Collections.singletonList(Scopes.PROFILE));
GoogleAccountCredential credential =
GoogleAccountCredential.usingOAuth2(LoginActivity.this, scopes);
credential.setSelectedAccount(
new Account(account.getEmail(), "com.google"));
People service = new People.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(name /* whatever you like */)
.build();
// All the person details
Person meProfile = null;
try {
meProfile = service.people().get("people/me").setRequestMaskIncludeField("people.AgeRange").execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
).start();
}
// [START auth_with_google]
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
// [START_EXCLUDE silent]
showProgressBar();
// [END_EXCLUDE]
AuthCredential credential = GoogleAuthProvider.getCredential(acct.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(getApplicationContext(), "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// [START_EXCLUDE]
cancelProgressBar();
// [END_EXCLUDE]
}
});
}
// [END auth_with_google]
private void firebaseSignUp()
{
Toast.makeText(LoginActivity.this, "Welcome to SignUpActivity",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), SignupActivity.class));
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
finish();
}
public void firebaseLogin()
{
loginFireBaseBtn.setEnabled(false);
showProgressBar();
final String email = loginEt.getText().toString();
final String password = passwordEt.getText().toString();
if (TextUtils.isEmpty(email))
{
cancelProgressBar();
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
loginFireBaseBtn.setEnabled(true);
return;
}
if (TextUtils.isEmpty(password))
{
cancelProgressBar();
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
loginFireBaseBtn.setEnabled(true);
return;
}
//authenticate user
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful())
{
// there was an error
if (password.length() < 6)
{
passwordEt.setError(getString(R.string.minimum_password));
}
else
{
Log.e("error auth",getString(R.string.auth_failed));
Toast.makeText(getApplicationContext(), getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
cancelProgressBar();
loginFireBaseBtn.setEnabled(true);
}
else
{
cancelProgressBar();
Intent intent = new Intent(getApplicationContext(), AdminActivity.class);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
startActivity(intent);
Intent intent = new Intent(getApplicationContext(), NonAdminACtivity.class);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
startActivity(intent);
finish();
}
}
});
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
}
Is there any mistake in the code above related to PEOPLE API due to which I am unable to retrieve the value?
Could anyone please help me out in this.
Thanks in advance.
And also is there a way to get the gender of the user from People API?