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()
Related
What actually i am doing here, When a user login to their account, Then i am checking that whatever they had verified their email address or not, If not then i am starting the EmailVerificationActivity.
From where when user click on SEND VERIFICATION EMAIL Button an Email Verification code will be sent to user's email address.
after that when user successfully verified their email address, when they click SEND VERIFICATION LINK Button again.
Instead of showing toast message
Toast.makeText(this, "Your email has been verified, Now you can login.", Toast.LENGTH_LONG).show();,
sending the Email Verification link again.
Why isEmailVerified() returning the false condition.
This is my EmailVerificationActivity
package com.socialcodia.sherewatan;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
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.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class EmailVerificationActivity extends AppCompatActivity {
private TextView tvEmailAddress;
private Button btnSendVerificationEmail, btnSignOut;
//Firebase
FirebaseAuth mAuth;
FirebaseUser mUser;
String email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email_verification);
//Init
tvEmailAddress = findViewById(R.id.tvEmailAddress);
btnSendVerificationEmail = findViewById(R.id.btnSendVerificationEmail);
btnSignOut = findViewById(R.id.btnSignOut);
//Firebase Init
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
// get and set email address
email = mUser.getEmail();
tvEmailAddress.setText(email);
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signOut();
}
});
btnSendVerificationEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isEmailVerified();
}
});
}
private void isEmailVerified()
{
if (mAuth.getCurrentUser()!=null)
{
boolean isEmailVerified = mAuth.getCurrentUser().isEmailVerified();
if (isEmailVerified)
{
Toast.makeText(this, "Your email has been verified, Now you can login.", Toast.LENGTH_LONG).show();
}
else
{
sendVerificationEmail();
}
}
}
private void sendVerificationEmail()
{
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Toast.makeText(EmailVerificationActivity.this, "Email verification link has been sent", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(EmailVerificationActivity.this, "Oops! Failed to send email verification link", Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendToLoginWithEmail()
{
Intent intent= new Intent(getApplicationContext(),LoginActivity.class);
intent.putExtra("email",email);
startActivity(intent);
finish();
}
private void signOut()
{
mAuth.signOut();
sendToLoginWithEmail();
}
}
You need to reload current user information. You see the data of the user your have from authentication are old and you need to retrieve the latest. Use the reload() method for that.
How i solved the error.
private void isEmailVerified()
{
mAuth.getCurrentUser().reload().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
if (mAuth.getCurrentUser()!=null)
{
boolean isEmailVerified = mAuth.getCurrentUser().isEmailVerified();
if (isEmailVerified)
{
Toast.makeText(getApplicationContext(), "Your email has been verified, Now you can login.", Toast.LENGTH_LONG).show();
}
else
{
sendVerificationEmail();
}
}
}
});
}
I used the following line to solve this problem
await FirebaseAuth.instance.currentUser!.reload();
When I log in through facebook, I am supposed to get some data from Facebook such as my email, name and profile picture. However, now I can't get the data anymore after I added these codes
#Override
public void onSuccess(LoginResult loginResult) {
final AccessToken accessToken = loginResult.getAccessToken();
GraphRequestAsyncTask request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
}
}).executeAsync();
Toast.makeText(getApplicationContext(), "Login Success with Facebook", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
I am supposed to get these Facebook datas in this activity
package com.example.musix.Musix;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.musix.MainActivity;
import com.example.musix.R;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.google.firebase.auth.FirebaseAuth;
import org.json.JSONException;
import org.json.JSONObject;
public class ViewProfile extends AppCompatActivity {
private ImageView circleImageView;
private TextView txtName,txtEmail;
private ImageButton Home;
private ImageButton Playlist;
private FirebaseAuth firebaseAuth;
private Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_profile);
circleImageView = (ImageView) findViewById(R.id.profile_icon);
txtName = findViewById(R.id.profile_name);
txtEmail = findViewById(R.id.profile_email);
Home = (ImageButton)findViewById(R.id.home);
Playlist = (ImageButton)findViewById(R.id.playlisticon);
firebaseAuth = FirebaseAuth.getInstance();
logout = (Button)findViewById(R.id.btnLogout);
//go to LoginScreen page
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
startActivity(new Intent(ViewProfile.this, LoginScreen.class));
}
});
//go to Playlist page
Playlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ViewProfile.this, Playlist.class));
}
});
//go to MainActivity page
Home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ViewProfile.this, MainActivity.class));
}
});
checkLoginStatus();
}
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null){
txtName.setText("");
txtEmail.setText("");
circleImageView.setImageResource(0);
}
else{
loaduserProfile(currentAccessToken);
}
}
};
//get Facebook profile data
private void loaduserProfile(AccessToken newAccessToken){
GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String email = object.getString("email");
String id = object.getString("id");
String image_url = "https://graph.facebook.com/"+id+ "/picture?type=normal";
txtEmail.setText(email);
txtName.setText(first_name +" "+last_name);
RequestOptions requestOptions = new RequestOptions();
requestOptions.dontAnimate();
Glide.with(ViewProfile.this).load(image_url).into(circleImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name, last_name, email, id");
request.setParameters(parameters);
request.executeAsync();
}
//display Facebook profile data if already logged in
private void checkLoginStatus(){
if(AccessToken.getCurrentAccessToken()!= null){
loaduserProfile(AccessToken.getCurrentAccessToken());
}
}
}
My facebook login page
package com.example.musix.Musix;
import android.app.ProgressDialog;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
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.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.musix.MainActivity;
import com.example.musix.R;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphRequestAsyncTask;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.tasks.OnCompleteListener;
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 org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
public class LoginScreen extends AppCompatActivity {
private EditText Username;
private EditText Password;
private Button Login;
private LoginButton FacebookLogin;
private ImageView circleImageView;
private TextView txtName,txtEmail;
private TextView userRegistration;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private TextView forgotPassword;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
Username = (EditText) findViewById(R.id.etName);
Password = (EditText) findViewById(R.id.etPassword);
Login = (Button) findViewById(R.id.btnLogin);
FacebookLogin = (LoginButton) findViewById(R.id.facebookLogin);
txtName = findViewById(R.id.profile_name);
txtEmail = findViewById(R.id.profile_email);
circleImageView = (ImageView) findViewById(R.id.profile_icon);
userRegistration = (TextView)findViewById(R.id.tvRegister);
forgotPassword = (TextView)findViewById(R.id.tvForgotPassword);
firebaseAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
finish();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((Username.length() > 0) && (Password.length() > 0)) ||(AccessToken.getCurrentAccessToken()!= null)){
validate(Username.getText().toString(), Password.getText().toString());
}
else if((Username.length() == 0) && (Password.length() > 0)){
Username.setError("Enter Username");
}
else if((Password.length() == 0) && (Username.length() > 0)){
Password.setError("Enter Password");
}
else{
Username.setError("Enter Username");
Password.setError("Enter Password");
}
}
});
userRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginScreen.this, SignUp.class));
}
});
callbackManager = CallbackManager.Factory.create();
FacebookLogin.setReadPermissions(Arrays.asList("email", "public_profile"));
checkLoginStatus();
FacebookLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
final AccessToken accessToken = loginResult.getAccessToken();
GraphRequestAsyncTask request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
}
}).executeAsync();
Toast.makeText(getApplicationContext(), "Login Success with Facebook", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Login Failed", Toast.LENGTH_SHORT).show();
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginScreen.this, ForgotPassword.class));
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null){
txtName.setText("");
txtEmail.setText("");
circleImageView.setImageResource(0);
}
else{
loaduserProfile(currentAccessToken);
}
}
};
//get Facebook profile data
private void loaduserProfile(AccessToken newAccessToken){
GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String email = object.getString("email");
String id = object.getString("id");
String image_url = "https://graph.facebook.com/"+id+ "/picture?type=normal";
txtEmail.setText(email);
txtName.setText(first_name +" "+last_name);
RequestOptions requestOptions = new RequestOptions();
requestOptions.dontAnimate();
Glide.with(LoginScreen.this).load(image_url).into(circleImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name, last_name, email, id");
request.setParameters(parameters);
request.executeAsync();
}
//display Facebook profile data if already logged in
private void checkLoginStatus(){
if(AccessToken.getCurrentAccessToken()!= null){
loaduserProfile(AccessToken.getCurrentAccessToken());
}
}
private void validate(String userUsername, String userPassword){
//show login progress
progressDialog.setMessage("Loading . . .");
progressDialog.show();
//Login admin account
if((userUsername.equals("Admin")) && (userPassword.equals("12345"))){
Intent intent = new Intent(LoginScreen.this, MainActivity.class);
startActivity(intent);
finish();
}
//Login using firebase-registered accounts
else{
firebaseAuth.signInWithEmailAndPassword(userUsername,userPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isComplete()){
progressDialog.dismiss();
Toast.makeText(LoginScreen.this, "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
else{
progressDialog.dismiss();
Toast.makeText(LoginScreen.this, "The username or password you entered is incorrect.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
}
}).executeAsync();
Here you are logging yourself out the moment you are succesfully logged in. Remove
LoginManager.getInstance().logOut();
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 CustomerLoginRegisterActivity.java that gets customer's Email and password for login and registers email and password to firebase if they don't have an account,
i refered this tutorial : https://youtu.be/d8JMjBMQaMk?list=PLxefhmF0pcPl6gcWvrpTbjGO7rcMWY1jT
But The Firebase authentication fails everytime during registration.
I've enabled Sign-In method in my Firebase Account
package com.example.saiadarsh.appendly;
import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class CustomerLoginRegisterActivity extends AppCompatActivity {
private Button CustomerLoginButton;
private Button CustomerRegisterButton;
private TextView CustomerRegisterLink;
private TextView CustomerStatus;
private EditText EmailCustomer;
private EditText PasswordCustomer;
private ProgressDialog loadingBar;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_login_register);
mAuth = FirebaseAuth.getInstance();
CustomerLoginButton = (Button) findViewById(R.id.customer_login_btn);
CustomerRegisterButton = (Button) findViewById(R.id.customer_register_btn);
CustomerRegisterLink = (TextView) findViewById(R.id.register_customer_link);
CustomerStatus = (TextView) findViewById(R.id.customer_status);
EmailCustomer = (EditText) findViewById(R.id.email_customer);
PasswordCustomer = (EditText) findViewById(R.id.password_customer);
loadingBar = new ProgressDialog(this);
CustomerRegisterButton.setVisibility(View.INVISIBLE);
CustomerRegisterButton.setEnabled(false);
CustomerRegisterLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CustomerLoginButton.setVisibility(View.INVISIBLE);
CustomerRegisterLink.setVisibility(View.INVISIBLE);
CustomerStatus.setText("Register Customer");
CustomerRegisterButton.setVisibility(View.VISIBLE);
CustomerRegisterButton.setEnabled(true);
}
});
CustomerRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
String email = EmailCustomer.getText().toString();
String password = PasswordCustomer.getText().toString();
RegisterCustomer(email, password);
}
});
CustomerLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = EmailCustomer.getText().toString();
String password = PasswordCustomer.getText().toString();
SignInCustomer(email, password);
}
});
}
private void SignInCustomer(String email, String password)
{
if(TextUtils.isEmpty(email))
{
Toast.makeText(CustomerLoginRegisterActivity.this, "Please write Email...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(password))
{
Toast.makeText(CustomerLoginRegisterActivity.this, "Please write Password...", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Customer Login");
loadingBar.setMessage("Please wait, while we are on it");
loadingBar.show();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if(task.isSuccessful())
{
Toast.makeText(CustomerLoginRegisterActivity.this, "Customer Login Successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else
{
Toast.makeText(CustomerLoginRegisterActivity.this, "Login Unsuccessful, Please Try Again.....", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void RegisterCustomer(String email, String password)
{
if(TextUtils.isEmpty(email))
{
Toast.makeText(CustomerLoginRegisterActivity.this, "Please write Email...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(password))
{
Toast.makeText(CustomerLoginRegisterActivity.this, "Please write Password...", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Customer Registration");
loadingBar.setMessage("Please wait, while we are on it");
loadingBar.show();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if(task.isSuccessful())
{
Toast.makeText(CustomerLoginRegisterActivity.this, "Customer Registered Successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else
{
Toast.makeText(CustomerLoginRegisterActivity.this, "Registeration Unsuccessful, Please Try Again.....", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
}
In the following code, I am trying to open a Login page. User will fill in email and password. When user clicks on login button, checkLogin method is called.
I understand that in the onComplete method, the 1st if block checking success (filling in email, password and clicking login) is not called. I always get the Toast message "Error login" (the else block).
package com.awani.pocketblog;
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.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
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;
public class LoginActivity extends AppCompatActivity {
private EditText mLoginEmailField;
private EditText mLoginPasswordField;
private Button mLoginButton;
private Button mNewAccountButton;
private FirebaseAuth mAuth;
private ProgressDialog mProgress;
private DatabaseReference mDatabaseUsers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabaseUsers.keepSynced(true);
mLoginEmailField = (EditText) findViewById(R.id.loginEmailField);
mLoginPasswordField = (EditText) findViewById(R.id.loginPaswordField);
mLoginButton = (Button) findViewById(R.id.loginButton);
mNewAccountButton = (Button) findViewById(R.id.newAccountButton);
mProgress = new ProgressDialog(this);
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkLogin();
}
});
}
private void checkLogin() {
//retrieve the data from database to check if user is logged in correctly
String email = mLoginEmailField.getText().toString().trim();
String password = mLoginPasswordField.getText().toString().trim();
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
mProgress.setMessage("Checking Login...");
mProgress.show();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener < AuthResult > () {
#Override
public void onComplete(#NonNull Task < AuthResult > task) {
//the following if block is never executed....WHY?
if (task.isSuccessful()) {
// Toast.makeText(LoginActivity.this,"hi",Toast.LENGTH_LONG).show();
checkUserExist();
} else {
mProgress.dismiss();
Toast.makeText(LoginActivity.this, "Error Login", Toast.LENGTH_LONG).show();
}
}
});
}
}
private void checkUserExist() {
//retrieving UID
final String user_id = mAuth.getCurrentUser().getUid();
//check if the user with thi UID already exists
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(user_id)) {
Intent mainIntent = new Intent(LoginActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
} else {
Intent setUpIntent = new Intent(LoginActivity.this, SetUpActivity.class);
setUpIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(setUpIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
For authentication with email/password, the user must first be created with createUserWithEmailAndPassword():
Tries to create a new user account with the given email address and
password. If successful, it also signs the user in into the app
This example is provided in Step 4 of the guide for password-based authentication:
mAuth.createUserWithEmailAndPassword(email, password)
.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, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
Go to your firebase console, enable sign-in method: Email/Password or Anonymous
If it does not work, please edit your password, maybe it's too short.