I want to create Phone Auth Credential like Uber, I mean when user use the app for the first time he has to complete his registration information after phone authentication then he will be able to move to DriverHome Activity, but next time he uses the authentication he will redirect to the DriverHome Activity automatically.
I've used Phone Auth Credential code and it works fine but I need to add the part is responsible for checking if the user registered before or not.
public class VerifyPhoneActivity extends AppCompatActivity {
private String verificationId;
private FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference users;
ProgressBar progressBar;
TextInputEditText editText;
AppCompatButton buttonSignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification_code);
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressbar);
editText = findViewById(R.id.editTextCode);
buttonSignIn = findViewById(R.id.buttonSignIn);
String phoneNumber = getIntent().getStringExtra("phoneNumber");
sendVerificationCode(phoneNumber);
// save phone number
SharedPreferences prefs = getApplicationContext().getSharedPreferences("USER_PREF",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("phoneNumber", phoneNumber);
editor.apply();
buttonSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = editText.getText().toString().trim();
if (code.isEmpty() || code.length() < 6) {
editText.setError("Enter code...");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(VerifyPhoneActivity.this, DriverHomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else {
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
private void sendVerificationCode(String number) {
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
progressBar.setVisibility(View.GONE);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
editText.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
};
}
before onCreateView
check if sharepreference has phone number if it has then using startActivity(new Intent(this, DriverHomeActivity.class); to go directly to driverhome activity
if sharepreference has no phone number then
Save phone number in sharepreference if onComplete function of signInWithCredential return successful using isSucessful
public class VerifyPhoneActivity extends AppCompatActivity {
private String verificationId;
private FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference users;
ProgressBar progressBar;
TextInputEditText editText;
AppCompatButton buttonSignIn;
SharedPreferences prefs ;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getApplicationContext().getSharedPreferences("USER_PREF",
Context.MODE_PRIVATE);
editor = prefs.edit();
//add this line
if(prefs.getString("phoneNumber", null) != null)
startActivity(new Intent(this, DriverHomeActivity.class));
setContentView(R.layout.activity_verification_code);
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressbar);
editText = findViewById(R.id.editTextCode);
buttonSignIn = findViewById(R.id.buttonSignIn);
String phoneNumber = getIntent().getStringExtra("phoneNumber");
sendVerificationCode(phoneNumber);
buttonSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = editText.getText().toString().trim();
if (code.isEmpty() || code.length() < 6) {
editText.setError("Enter code...");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
//insert data if task is successful
editor.putString("phoneNumber", phoneNumber);
editor.apply();
Intent intent = new Intent(VerifyPhoneActivity.this, DriverHomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else {
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
private void sendVerificationCode(String number) {
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
progressBar.setVisibility(View.GONE);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
editText.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
};
Related
I'm trying to authenticate user with phone number using the firebase Authentication method. But it is showing me error after some time by running the code. And I think the sendVerificationCodeToUser() function is not working properly.
package com.example.foodapp;
import ...
public class PhoneVerification<phoneAuthProvider> extends AppCompatActivity {
String verificationCodeBySystem;
Button btn_verify;
EditText phoneenteredbyuser;
ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_verification);
btn_verify = findViewById(R.id.btn_verify);
phoneenteredbyuser = findViewById(R.id.txt_otp);
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.GONE);
String phoneNo = getIntent().getStringExtra("phone");
sendVerificationCodeToUser(phoneNo);
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code= phoneenteredbyuser.toString();
if(code.isEmpty() || code.length()< 6){
phoneenteredbyuser.setError("Wrong OTP...");
phoneenteredbyuser.requestFocus();
return;
}
progressbar.setVisibility(View.VISIBLE);
verifyCode(code);
}
});
}
private void sendVerificationCodeToUser(String phoneNo) {
FirebaseAuth mAuth= FirebaseAuth.getInstance();
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber("+92" + phoneNo) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override //Entering OTP by manual way
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationCodeBySystem = s;
}
#Override // Automatically Verifying the OTP by system.
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
progressbar.setVisibility(View.VISIBLE);
verifyCode(code);
}
}
#Override //In case of error this code will run.
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(PhoneVerification.this, "Error Occured", Toast.LENGTH_SHORT).show();
}
};
private void verifyCode(String codeByUser) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCodeBySystem, codeByUser);
signInUserByCredentials(credential);
}
private void signInUserByCredentials(PhoneAuthCredential credential) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(PhoneVerification.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(PhoneVerification.this, "Your Account has been created successfully!", Toast.LENGTH_SHORT).show();
//Perform Your required action here to either let the user sign In or do something required
Intent intent = new Intent(getApplicationContext(), User_Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
Toast.makeText(PhoneVerification.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
After pressing verify button to send me the code the application opens browser and wait sometime. Nothing happens and no SMS sent to me and this toast appears to me. before you ask i made everything before, firebase and and SHA certificate fingerprints.
public class PhoneSingUp extends AppCompatActivity {
private FirebaseAuth auth;
TextView SignUpTXT , VerifyingTXT , ErrorTXT ;
GifImageView VerifySuccess ;
Button VerifyBTN , ContinueBTN ;
CountryCodePicker ccp;
EditText NumberEnt;
PinView VerifyPIN;
String VerifyCodeBySystem , Code , CountryCodeS ,UserEnteredNumber , PhoneNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_sing_up);
auth = FirebaseAuth.getInstance();
SignUpTXT = findViewById(R.id.SingUpTXT);
ccp = (CountryCodePicker) findViewById(R.id.ccp);
NumberEnt = (EditText) findViewById(R.id.editText_carrierNumber);
VerifyingTXT = findViewById(R.id.verifyingTXT);
ErrorTXT = findViewById(R.id.ErrorTXT);
VerifyPIN = findViewById(R.id.VerificationPIN);
VerifySuccess = findViewById(R.id.VerifySuccess);
VerifyBTN = findViewById(R.id.VerifyBTN);
VerifyBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CountryCodeS = ccp.getSelectedCountryCode();
UserEnteredNumber = NumberEnt.getText().toString();
PhoneNumber = "+" + CountryCodeS + UserEnteredNumber;
if (PhoneNumber.length() < 13){
ErrorTXT.setVisibility(View.VISIBLE);
VerifyingTXT.setVisibility(View.INVISIBLE);
}else {
if (PhoneNumber.length() == 13) {
ErrorTXT.setVisibility(View.GONE);
VerifyingTXT.setVisibility(View.VISIBLE);
sendVerificationCode(PhoneNumber);
}
}
}
});
ContinueBTN = findViewById(R.id.ContinueBTN);
ContinueBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(PhoneSingUp.this, MainActivity.class));
finish();
}
});
}
private void sendVerificationCode(String phoneNumber) {
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(PhoneSingUp.this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
VerifyCodeBySystem = s;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
Code = phoneAuthCredential.getSmsCode();
if (Code != null){
VerifyPIN.setText(Code);
VerifyCode(Code);
VerifySuccess.setVisibility(View.VISIBLE);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(PhoneSingUp.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
};
private void VerifyCode(String code) {
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(VerifyCodeBySystem,code);
signInWithPhoneAuthCredential(phoneAuthCredential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
auth.signInWithCredential(phoneAuthCredential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
}
}
}
});
}
}
I'm creating an Android application and am implementing the login / register functionality.
I'm at the stage where the register activity is successfully creating user entries in my Firebase application, however, I can't seem to track if the task was successful.
private void startRegister() {
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
String confirmPassword = mConfirmPassword.getText().toString();
// Check that fields are not empty
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
Toast.makeText(Register.this, "Email, password or confirm password field cannot be empty.", Toast.LENGTH_LONG).show();
} else if (!password.equals(confirmPassword)) {
Toast.makeText(Register.this, "Password and confirm password should match", Toast.LENGTH_LONG).show();
} else {
mAuth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(Register.this, "Success", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Register.this, "Failure", Toast.LENGTH_LONG).show();
}
});
}
}
Both the if !task.isSuccessful() or else blocks ever get reached but the user is created in Firebase. Any ideas why I can't track the success/if it failed?
IN COMPARISON:
This is working in my login class.
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(Login.this, "Credentials error, user may not exist.", Toast.LENGTH_LONG).show();
}
}
});
Hard to say what's going with the current way of implementation.
Try adding a onSuccess directly
mAuth.createUserWithEmailAndPassword(email, pass).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
//done
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//display toast if registering failed
ToastRect.failed(RegisterActivity.this, getString(R.string.app_activities_error_text)
}
});
public class Register extends AppCompatActivity {
private EditText mEmailField;
private EditText mPasswordField;
private EditText mConfirmPassword;
private Button mRegisterButton;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseApp.initializeApp(this);
setContentView(R.layout.activity_register);
mEmailField = findViewById(R.id.registerEmailField);
mPasswordField = findViewById(R.id.registerPasswordField);
mConfirmPassword = findViewById(R.id.registerConfirmPassword);
mRegisterButton = findViewById(R.id.registerButton);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(Register.this, UploadActivity.class));
}
}
};
// https://stackoverflow.com/questions/10936042/how-to-open-layout-on-button-click-android
Button register = (Button) findViewById(R.id.navigate_to_login);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Login.class);
startActivityForResult(myIntent, 0);
}
});
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startRegister();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void startRegister() {
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
String confirmPassword = mConfirmPassword.getText().toString();
// Check that fields are not empty
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
Toast.makeText(Register.this, "Email, password or confirm password field cannot be empty.", Toast.LENGTH_LONG).show();
} else if (!password.equals(confirmPassword)) {
Toast.makeText(Register.this, "Password and confirm password should match", Toast.LENGTH_LONG).show();
} else {
mAuth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(Register.this, "Success", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Register.this, "Failure", Toast.LENGTH_LONG).show();
}
});
}
}
}
To confirm the FirebaseAuth.AuthStateListener() was kicking in. This was a bad copy and paste job from the my Login class. This was stopping me handle the successful user creation.
The fix then looked like:
public class Register extends AppCompatActivity {
private EditText mEmailField;
private EditText mPasswordField;
private EditText mConfirmPassword;
private Button mRegisterButton;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseApp.initializeApp(this);
setContentView(R.layout.activity_register);
mEmailField = findViewById(R.id.registerEmailField);
mPasswordField = findViewById(R.id.registerPasswordField);
mConfirmPassword = findViewById(R.id.registerConfirmPassword);
mRegisterButton = findViewById(R.id.registerButton);
mAuth = FirebaseAuth.getInstance();
// https://stackoverflow.com/questions/10936042/how-to-open-layout-on-button-click-android
Button register = (Button) findViewById(R.id.navigate_to_login);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Login.class);
startActivityForResult(myIntent, 0);
}
});
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startRegister();
}
});
}
#Override
protected void onStart() {
super.onStart();
}
private void startRegister() {
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
String confirmPassword = mConfirmPassword.getText().toString();
// Check that fields are not empty
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
Toast.makeText(Register.this, "Email, password or confirm password field cannot be empty.", Toast.LENGTH_LONG).show();
} else if (!password.equals(confirmPassword)) {
Toast.makeText(Register.this, "Password and confirm password should match", Toast.LENGTH_LONG).show();
} else {
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(Register.this, "Password and confirm password should match", Toast.LENGTH_LONG).show();
}
}
});
}
}
}
I enter my main activity, inside the MainActivity I have registration, after the registartion accure I want to log out from firebase so that he doesn't remember me.
Because when I retured to the MainActivity after the signout he still remembers the previous user when I register as a new user. This occurs only after logging and logout immediately. Btw, if I run the app its working fine. The problem is only when I signout and then going to RegistrationActivity to register another user.
Here is the MainActivity code:
public class MainActivity extends AppCompatActivity {
private SignInButton signIn;
private int RC_SIGN_IN=1;
private GoogleSignInClient mGoogleSignInClient;
private String TAG = "MainActivity";
private FirebaseAuth mAuth;
private Button registration;
private EditText email;
private EditText password;
private Button login;
private BottomNavigationView bottomNavigationItemView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signIn = (SignInButton)findViewById(R.id.sign_in_button);
mAuth = FirebaseAuth.getInstance();
registration = (Button) findViewById(R.id.registrate);
email = (EditText)findViewById(R.id.email);
password = (EditText)findViewById(R.id.password);
login = (Button)findViewById(R.id.login);
bottomNavigationItemView = (BottomNavigationView)findViewById(R.id.navB) ;
bottomNavigationItemView.getMenu().getItem(0).setChecked(true);
bottomNavigationItemView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.register_menu: {
Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(intent);
break;
}
}
return true;
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
registration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(intent);
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email_text = email.getText().toString().trim();
String password_text = password.getText().toString().trim();
if(TextUtils.isEmpty(email_text) || TextUtils.isEmpty(password_text))
{
Toast.makeText(MainActivity.this, "One or more fields are empty", Toast.LENGTH_LONG).show();
}
else
{
mAuth.signInWithEmailAndPassword(email_text, password_text).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful())
{
Toast.makeText(MainActivity.this, "Sign in problem", Toast.LENGTH_LONG).show();
}
else
{
Intent intent = new Intent(MainActivity.this, AccountActivity.class);
startActivity(intent);
}
}
});
}
}
});
}
private void signIn() { /*Sign in to the app with Google Account*/
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from 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);
try{
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
}
catch(ApiException e){
Log.w(TAG, "Google Sin in Failed");
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct)
{
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if(task.isSuccessful())
{
Log.d(TAG, "signInWithCredential: success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
}
else
{
Log.w(TAG, "signInWithCredential: failure", task.getException()); /*In case of unsuccessful login*/
Toast.makeText(MainActivity.this, "You are not able to log in to Google", Toast.LENGTH_LONG).show();
//updateUI(null);
}
}
});
}
private void updateUI(FirebaseUser user) /*In case of successful registration*/
{
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if (acct != null) {
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
Toast.makeText(this, "Name of User : " + personName + "UserId is : " + personId, Toast.LENGTH_LONG);
Intent intent = new Intent(this, AccountActivity.class);
intent.putExtra("personPhoto", personPhoto.toString());
startActivity(intent);
}
}
Here is the AccountActivity code:
public class AccountActivity extends AppCompatActivity {
private GoogleSignInClient mGoogleSignInClient;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private CardView signOut;
private CardView ratingTable;
private CardView settings;
private CardView map;
private CardView favoritePlaces;
DatabaseReference databaseReference;
FirebaseDatabase database;
List<User> users;
CollapsingToolbarLayout collapsingToolbarLayout;
String photoString="No photo";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
mAuth = FirebaseAuth.getInstance();
signOut = (CardView) findViewById(R.id.logout);
ratingTable = (CardView) findViewById(R.id.rating);
settings = (CardView)findViewById(R.id.settings);
map = (CardView) findViewById(R.id.map);
favoritePlaces = (CardView)findViewById(R.id.favorite);
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference();
users = new ArrayList<User>();
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collaps);
if(mAuth.getCurrentUser().getDisplayName()!=null)
{
Intent i = getIntent();
photoString = i.getStringExtra("personPhoto");
}
databaseReference.child("user").addValueEventListener(new ValueEventListener() { /*A new user is registered in the database*/
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
for (DataSnapshot child : children) {
User user = child.getValue(User.class);
users.add(user);
}
if (!findUser()) /*If the user is not found, this is a new user and must be registered*/
addUser();
showName(); /*A user-specific message*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mAuth.getCurrentUser().getDisplayName()!=null)
{
mGoogleSignInClient.signOut();
//Intent intent = new Intent(AccountActivity.this, MainActivity.class);
// startActivity(intent);
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
else
{
mAuth.signOut();
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, SettingsActivity.class);
startActivity(intent);
}
});
map.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, MapsActivity.class);
startActivity(intent);
}
});
favoritePlaces.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, favoritePlacesActivity.class);
startActivity(intent);
}
});
ratingTable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, RatingTableActivity.class);
startActivity(intent);
}
});
}
private void showName() /*A user-specific message*/
{
String name = "";
String userId = mAuth.getUid();
for (User tmpUser : users) {
if (userId.equals(tmpUser.getUserId()))
{
name = tmpUser.getUserName();
break;
}
}
collapsingToolbarLayout.setTitle("Hi " + name);
}
private boolean findUser() /*Check if a logged-on user is already registered in the database*/
{
FirebaseUser user = mAuth.getCurrentUser();
String userId = mAuth.getUid();
for (User tmpUser : users) {
if (userId.equals(tmpUser.getUserId())) {
return true;
}
}
return false;
}
private void addUser() /*In case of registration from Google Account*/
{
String userId = mAuth.getUid();
if(mAuth.getCurrentUser().getDisplayName()!=null) /*In case of registration not from Google Account*/
{
databaseReference = FirebaseDatabase.getInstance().getReference("user");
FirebaseUser user = mAuth.getCurrentUser();
String userName = user.getDisplayName();
User newUser = User.getInstance(userId, userName, photoString);
databaseReference.child(userId).setValue(newUser);
}
else /*If the user is not registered the function registers it in the database*/
{
databaseReference = FirebaseDatabase.getInstance().getReference("user");
Intent i = getIntent();
String firstName = i.getStringExtra("firstName");
String lastName = i.getStringExtra("lastName");
User newUser = User.getInstance(userId, firstName + " " + lastName, photoString);
databaseReference.child(userId).setValue(newUser);
}
}
RegistrationActivity code:
public class RegistrationActivity extends AppCompatActivity {
EditText email_text;
EditText pass1;
EditText pass2;
EditText first;
EditText last;
Button registrate;
FirebaseAuth mAuth;
private ProgressDialog progressDialog;
private BottomNavigationView bottomNavigationItemView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
mAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
email_text = (EditText)findViewById(R.id.email);
pass1 = (EditText)findViewById(R.id.password1);
pass2 = (EditText)findViewById(R.id.password2);
first = (EditText)findViewById(R.id.first_name);
last = (EditText)findViewById(R.id.last_name);
registrate = (Button)findViewById(R.id.registrate);
bottomNavigationItemView = (BottomNavigationView)findViewById(R.id.navB) ;
bottomNavigationItemView.getMenu().getItem(1).setChecked(true);
bottomNavigationItemView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.Signin_menu: {
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
break;
}
}
return true;
}
});
registrate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = email_text.getText().toString().trim();
String password1 = pass1.getText().toString().trim();
String password2 = pass2.getText().toString().trim();
final String first_name = first.getText().toString().trim();
final String last_name = last.getText().toString().trim();
boolean correctFlag=true;
/*All tests for input integrity*/
if(!password1.equals(password2))
{
Toast.makeText(RegistrationActivity.this, "The password does not match", Toast.LENGTH_LONG).show();
correctFlag=false;
}
if(password1.equals("") && password2.equals(""))
{
Toast.makeText(RegistrationActivity.this, "No password entered", Toast.LENGTH_LONG).show();
correctFlag=false;
}
if(email.equals("") || first_name.equals("") || last_name.equals(""))
{
Toast.makeText(RegistrationActivity.this, "One or more of the parameters are incorrect", Toast.LENGTH_LONG).show();
correctFlag=false;
}
if(correctFlag) /*There is no problem filling the fields*/
{
progressDialog.setMessage("Registrating user...");
progressDialog.show();
mAuth.createUserWithEmailAndPassword(email, password1).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
Toast.makeText(RegistrationActivity.this, "Registered Succesfully", Toast.LENGTH_SHORT).show();
progressDialog.cancel();
Intent intent = new Intent(RegistrationActivity.this, AccountActivity.class);
intent.putExtra("firstName", first_name);
intent.putExtra("lastName", last_name);
startActivity(intent);
}
else
{
Toast.makeText(RegistrationActivity.this, "could not register. please try again", Toast.LENGTH_SHORT).show();
progressDialog.cancel();
}
}
});
}
}
});
}
You need to log out of GoogleSignInClient :
public void signOut() {
signOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(getContext(), gso);
mGoogleSignInClient.signOut();
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getContext(), LoginActivity.class));
}
});
}
The Firebase Auth is not starting on HomeActivitiy on button click.
It only works where reopen the application.
public class Auth1Activity extends AppCompatActivity {
String string_1;
String string_2;
private static final Boolean CHECK_EMAIL_VERIFIED = false;
private static final String TAG = "LoginActivity";
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser firebaseUser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auth_1);
firebaseAuth = FirebaseAuth.getInstance();
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
}
};
firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
Intent intent = new Intent(Auth1Activity.this, HomeActivity.class);
startActivity(intent);
finish();
}
final EditText auth_layout_1_edit_text_1 = findViewById(R.id.auth_layout_1_edit_text_1);
final EditText auth_layout_1_edit_text_2 = findViewById(R.id.auth_layout_1_edit_text_2);
Button auth_layout_1_button = findViewById(R.id.auth_layout_1_button);
auth_layout_1_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
string_1 = auth_layout_1_edit_text_1.getText().toString();
string_2 = auth_layout_1_edit_text_2.getText().toString();
if (string_1.matches("") && string_2.matches("")) {
auth_layout_1_edit_text_1.setError("Enter Email Address");
auth_layout_1_edit_text_2.setError("Enter Password");
} else if (!string_1.matches("") && !string_2.matches("")) {
firebaseAuth.signInWithEmailAndPassword(string_1, string_2)
.addOnCompleteListener(Auth1Activity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
try {
if (firebaseUser.isEmailVerified()) {
Intent intent = new Intent(Auth1Activity.this, HomeActivity.class);
startActivity(intent);
finish();
} else if (!firebaseUser.isEmailVerified()) {
Toast.makeText(Auth1Activity.this, "Sign Up Error Please Try Again.", Toast.LENGTH_SHORT).show();
}
} catch (NullPointerException ignored) {
}
}
});
}
}
});
}
#Override
public void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(authStateListener);
}
#Override
public void onStop() {
super.onStop();
if (authStateListener != null) {
firebaseAuth.removeAuthStateListener(authStateListener);
}
}
}
What could be going wrong?
Try this way
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
Intent intent = new Intent(Auth1Activity.this, HomeActivity.class);
startActivity(intent);
finish();
}
}
};