In my app, First, I am verifying phone numbers by using phone authentication of firebase.
I am doing this process in the OTPVerificationActivity class. Every thing is working fine in this class, I am getting the OTP code also and the user gets signed in.
If the phone number is verified, then I am verifying the email by sending the verification email. I am doing this process in the EmailVerificationActivity class. In this class first, i am checking is the user exists or not. if the user is there, then I am logging out the user.
Then i create the account using createUserWithEmailAndPassword function. After this, i want to send a verification email to the user.
PROBLEM:- Now the problem is, after creating the account,onCreate method gets called again. Due to this, I am unable to send the verification email and the further task. So how to stop onCreate method from getting called again.
NOTE :-
I tried to run only EmailVerificationActivity not OTPVerificationActivity.
In that case every thing was working properly. I was able to send verification email and also able to verify the user.
But when i am using the OTPVerificationActivityand EmailVerificationActivity together i am getting this problem.
So please help me to solve this problem.
public class OTPVerificationActivity extends AppCompatActivity {
String verificationID;
TextView messageTV;
EditText OTPET;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthStateListener;
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationID = s;
Log.i("onSend",s);
}
};
String phoneNumber;
public void sendVerificationCode(View view)
{
String code = OTPET.getText().toString();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationID,code);
signInWithCredential(credential);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otpverification);
messageTV = (TextView) findViewById(R.id.messageTextView);
OTPET = (EditText) findViewById(R.id.OTPEditText);
mAuth = FirebaseAuth.getInstance();
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() != null)
{
firebaseAuth.signOut();
if(firebaseAuth.getCurrentUser() == null)
{
Intent intent = new Intent(OTPVerificationActivity.this,EmailVerification.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
else
{
Log.i("firebaseAuth","user is not null");
}
}
}
};
String message = "Please type the verification code sent to ";
messageTV.setText(message+" " + "+91 " + getIntent().getStringExtra("phoneNumber"));
phoneNumber = "+91" + getIntent().getStringExtra("phoneNumber");
sendPhoneNumber(phoneNumber);
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onDestroy() {
super.onDestroy();
if(mAuth.getCurrentUser() != null)
{
mAuth.signOut();
}
}
public void sendPhoneNumber(String number)
{
Log.i("sendPhoneNumber","inside it");
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
Log.i("sendPhoneNumber","outside it");
}
private void signInWithCredential(final PhoneAuthCredential credential)
{
mAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful())
{
Toast.makeText(OTPVerificationActivity.this, "Sign in Failed.", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(OTPVerificationActivity.this, "Phone number verified.", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("FailedListener",e.getMessage());
}
});
}
}
Below is the code of EmailVerificationActivity class.
public class EmailVerification extends AppCompatActivity {
EditText emailET, passwordET, confirmPasswordET;
AlertDialog.Builder builder;
AlertDialog alertDialog;
ProgressDialog progressDialog;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthStateListener;
public void login(View view)
{
startActivity(new Intent(EmailVerification.this,MainActivity.class));
}
public void submit(View view)
{
String email = emailET.getText().toString();
String password = passwordET.getText().toString();
String confirmPassword = confirmPasswordET.getText().toString();
if(!(TextUtils.isEmpty(email) && TextUtils.isEmpty(password)))
{
if(password.equals(confirmPassword))
{
progressDialog.show();
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
//acount created...
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.i("verificationEmail","send");
progressDialog.dismiss();
if(!EmailVerification.this.isFinishing())
{
alertDialog.show();
}
Toast.makeText(EmailVerification.this, "Email send successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("verificationEmail","Not send");
//failed to create account...
progressDialog.dismiss();
Toast.makeText(EmailVerification.this, "Failed to create account", Toast.LENGTH_SHORT).show();
}
});
}
else
{
//account not created...
progressDialog.dismiss();
Log.i("taskNotSuccessful",task.getException().getMessage());
Toast.makeText(EmailVerification.this, "Problem in creating account", Toast.LENGTH_SHORT).show();
}
}
});
}
else
{
Toast.makeText(this, "Confirm Password is not same as Password.", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(this, "Fields are empty.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email_verification);
Log.i("onCreate","inside it");
initializeWidgets();
progressDialog = new ProgressDialog(EmailVerification.this);
progressDialog.setMessage("Sending verification email.");
builder= new AlertDialog.Builder(EmailVerification.this);
builder.setTitle("Email Verification")
.setMessage("We sent you a verification email, Please verify email before moving further.")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(EmailVerification.this,SignInActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
alertDialog = builder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(R.style.MyProgressDialogStyle);
}
});
mAuth = FirebaseAuth.getInstance();
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() != null)
{
// user is signed up...
Log.i("mAuthStateChanged","user is not null.");
}
else
{
Log.i("mAuthStateChanged","user is null");
}
}
};
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthStateListener);
}
private void initializeWidgets()
{
emailET = (EditText) findViewById(R.id.EmailEditText);
passwordET = (EditText) findViewById(R.id.PasswordEditText);
confirmPasswordET = (EditText) findViewById(R.id.ConfirmPasswordEditText);
}
}
This is the android life cycle. onCreate() will be called again, if your activity was destroyed due to release memory, explicitly killing and etc.
When you switch activities usually activities won't get killed. but it may be killed in some cases. so please move your codes from onCreate() to somewhere else.
You can not control android life cycle. It will happen anyway. therefore you need to obey them
Related
My App having the Phone authentication method for user register and login to firebase is working fine for some devices but in one device it had send the verification SMS only the first time i checked it. After that ,I even deleted that account from firebase console but it is not sending any verfication code on registering that number again.
public class phone_no_verification extends AppCompatActivity {
ProgressBar verify_progress;
TextInputEditText verify_edittext;
TextInputLayout verify_textInput;
String mverificationID;
FirebaseAuth auth;
static String TAG;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_no_verification);
verify_progress = findViewById(R.id.verify_progress);
verify_edittext = findViewById(R.id.verify_edittext);
verify_textInput = findViewById(R.id.verify_textinputLayout);
auth = FirebaseAuth.getInstance();
//getting Intent mobile number
Intent intent = getIntent();
String mobile = intent.getStringExtra("mobile_no");
sendVerificationcode(mobile);
//Entering code manually
findViewById(R.id.verify_Button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = verify_edittext.getText().toString().trim();
if(code.isEmpty() || code.length() < 6){
verify_textInput.setError("Enter Valid code");
}
else{
verifyVerificationCode(code);}
}
});
}
private void sendVerificationcode(String mobile) {
PhoneAuthProvider.getInstance().verifyPhoneNumber
("+91" + mobile,60, TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,mcallbacks);
}
//callback to detect verification status
PhoneAuthProvider.OnVerificationStateChangedCallbacks mcallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
mverificationID = s;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
Log.d(TAG, "onVerificationCompleted:" + phoneAuthCredential);
String code = phoneAuthCredential.getSmsCode();
if(code != null){
verify_edittext.setText(code);
verifyVerificationCode(code);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(phone_no_verification.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};
private void verifyVerificationCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mverificationID,code);
//signing user
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
auth.signInWithCredential(credential).addOnCompleteListener(phone_no_verification.this
, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Intent intent = new Intent(phone_no_verification.this, Basic_activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
sp = getSharedPreferences("login",MODE_PRIVATE);
sp.edit().putBoolean("isAutheticated",true).apply();
}
else{
String message = "Somthing is wrong, we will fix it soon...";
if(task.getException() instanceof FirebaseAuthInvalidCredentialsException){
message = "Invalid code Entered..";
}
else if(task.getException() instanceof FirebaseAuthUserCollisionException){
message = "User Already Exists";
}
Toast.makeText(phone_no_verification.this,message,Toast.LENGTH_LONG).show();
}
}
});
}
}
public class MainActivity extends AppCompatActivity {
EditText editTextPhone, editTextCode;
FirebaseAuth mAuth;
String codeSent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
editTextCode = findViewById(R.id.editTextCode);
editTextPhone = findViewById(R.id.editTextPhone);
findViewById(R.id.buttonGetVerificationCode).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendVerificationCode();
}
});
findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verifySignInCode();
}
});
}
private void verifySignInCode(){
String code = editTextCode.getText().toString();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeSent, code);
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//here you can open new activity
Toast.makeText(getApplicationContext(),
"Login Successfull", Toast.LENGTH_LONG).show();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(getApplicationContext(),
"Incorrect Verification Code ", Toast.LENGTH_LONG).show();
}
}
}
});
}
private void sendVerificationCode(){
String phone = editTextPhone.getText().toString();
if(phone.isEmpty()){
editTextPhone.setError("Phone number is required");
editTextPhone.requestFocus();
return;
}
if(phone.length() < 10 ){
editTextPhone.setError("Please enter a valid phone");
editTextPhone.requestFocus();
return;
}
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phone, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(FirebaseException e) {
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
codeSent = s;
}
};
}
Firebase not sending a auth code to mobile for verification please check what is the problem
because if your already regiter a number then 2nd time doesnot send if you want to try them to get otp then delete a number from firebase auth and try again
I'm creating an app for Android phones and using Firebase OTP authentication but I'm not sure if the codes are wrong or there's really an issue with Firebase sending SMS as what I've read as I have searched so far. Any help would be greatly appreciated!
This is the code:
public class MainActivity extends AppCompatActivity {
Button btSendCode;
Button btResend;
Button btVerify;
EditText etPhoneNumber;
EditText etEnterCode;
TextView tvGoHere;
String phoneVerificationID;
FirebaseAuth auth;
PhoneAuthProvider.OnVerificationStateChangedCallbacks verificationCallbacks;
PhoneAuthProvider.ForceResendingToken resendToken;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btSendCode = (Button) findViewById(R.id.button_sendcode);
btResend = (Button) findViewById(R.id.button_resend);
btVerify = (Button) findViewById(R.id.button_verify);
etPhoneNumber = (EditText) findViewById(R.id.edittext_phonenumber);
etEnterCode = (EditText) findViewById(R.id.edittext_entercode);
tvGoHere = (TextView) findViewById(R.id.textview_gohere);
auth = FirebaseAuth.getInstance();
}
public void clickSendCode(View view) {
etPhoneNumber.setVisibility(View.INVISIBLE);
btSendCode.setVisibility(View.INVISIBLE);
etEnterCode.setVisibility(View.VISIBLE);
btResend.setVisibility(View.VISIBLE);
btVerify.setVisibility(View.VISIBLE);
//firebase code
String phoneNumber = etPhoneNumber.getText().toString();
setUpVerificationCallbacks();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber,
120,
TimeUnit.SECONDS,
this,
verificationCallbacks
);
}
public void setUpVerificationCallbacks() {
verificationCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
signInWithPhoneAuthCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
if(e instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(MainActivity.this, "Invalid phone format", Toast.LENGTH_SHORT).show();
} else if(e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(MainActivity.this, "Too many requests", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String verificationID, PhoneAuthProvider.ForceResendingToken token) {
phoneVerificationID = verificationID;
resendToken = token;
}
};
}
public void clickVerifyCode(View view) {
String code = etEnterCode.getText().toString();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(phoneVerificationID, code);
signInWithPhoneAuthCredential(credential);
}
public void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
auth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
FirebaseUser user = task.getResult().getUser();
} else {
if(task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(MainActivity.this, "Invalid code", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void clickResendCode(View view) {
String phoneNumber = etPhoneNumber.getText().toString();
setUpVerificationCallbacks();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber,
120,
TimeUnit.SECONDS,
this,
verificationCallbacks,
resendToken
);
}
public void onClickGoHere(View view) {
Intent intentLogin = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intentLogin);
}
}
Phone number must begin with +, followed by country code and followed by number. Example: +9195021*****. And enable phone authentication sign method .
I'm making an Android project, and for starters I have been figuring out how signing up works. By the way, I used Firebase for this. Here's my code:
package com....
import...
public class MainActivity extends AppCompatActivity {
//VIEW AND WIDGETS
Button createUser, moveToLoginBtn;
EditText userEmailEdit, userPasswordEdit;
//FIREBASE AUTH FIELDS
FirebaseAuth nAuth;
FirebaseAuth.AuthStateListener nAuthlistener;
DatabaseReference mDatabaseRef, mUserCheckData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ASSIGN ID
createUser = (Button) findViewById(R.id.createUserBtn);
moveToLoginBtn = (Button) findViewById(R.id.moveToLogin);
userEmailEdit = (EditText) findViewById(R.id.emailEditTextCreate);
userPasswordEdit = (EditText) findViewById(R.id.passEditTextCreate);
//ASSIGN INSTANCE
mDatabaseRef = FirebaseDatabase.getInstance().getReference();
mUserCheckData = FirebaseDatabase.getInstance().getReference().child("Users");
nAuth = FirebaseAuth.getInstance();
nAuthlistener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
final String emailForVer = user.getEmail();
mUserCheckData.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
checkUserValidation(dataSnapshot, emailForVer);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
}
}
};
//ON CLICK LISTENER
createUser.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final String userEmailString, userPassString;
userEmailString = userEmailEdit.getText().toString().trim();
userPassString = userPasswordEdit.getText().toString().trim();
if (!TextUtils.isEmpty(userEmailString) && !TextUtils.isEmpty(userPassString))
{
nAuth.createUserWithEmailAndPassword(userEmailString,userPassString).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
DatabaseReference mChildDatabase = mDatabaseRef.child("Users").push();
String key_user = mChildDatabase.getKey();
mChildDatabase.child("isVerified").setValue("unverified");
mChildDatabase.child("userKey").setValue(key_user);
mChildDatabase.child("emailUser").setValue(userEmailString);
mChildDatabase.child("passWordUser").setValue(userPassString);
Toast.makeText(MainActivity.this, "User Account Created!", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, Profile.class));
}
else
{
Toast.makeText(MainActivity.this, "User Account Creation Fail", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, MainActivity.class));
}
}
});
}
}
});
//MOVE TO LOGIN
moveToLoginBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
});
}
private void checkUserValidation(DataSnapshot dataSnapshot, String emailForVer) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext())
{
DataSnapshot dataUser = (DataSnapshot) iterator.next();
if(String.valueOf(dataUser.child("emailUser").getValue()).equals(emailForVer) && dataUser.child("emailUser") != null)
{
if(String.valueOf(dataUser.child("isVerified").getValue()).equals("unverified") && dataUser.child("isVerified") != null)
{
Intent in = new Intent(MainActivity.this, Profile.class);
in.putExtra("USER_KEY" , String.valueOf(dataUser.child("userKey").getValue()));
startActivity(in);
//in.putExtra("NAME_KEY" , String.valueOf(dataUser.child("nameKey").getValue()));
}else
{
startActivity(new Intent(MainActivity.this, Welcome.class));
}
}
}
}
#Override
protected void onStart() {
super.onStart();
nAuth.addAuthStateListener(nAuthlistener);
}
#Override
protected void onStop() {
super.onStop();
nAuth.removeAuthStateListener(nAuthlistener);
}
}
I think I have implemented my methods correctly. But it toasts:
User Account Creation Failed
Is my
checkUseValidation() method wrong? Any kind of help is appreciated.
Also please pay attention to my:
public void onComplete
method, I have set it right I think. I don't know why the data isn't getting saved to the firebase database. Or why is the task unsuccesful as show in line:
if (task.isSuccessful())
Thank you very much.
First, you should change the toast, in your fail condition, to
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
So that you get what wrong in the task.
But before that did you enable Email/Password in the console????
See Sign up new users from url: https://firebase.google.com/docs/auth/android/start/?authuser=0
If task.isSuccessful() is false.You can add this to get error
Log.w(TAG, "createUserWithEmail:failure",task.getException());
Update you code as:
createUser.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final String userEmailString, userPassString;
userEmailString = userEmailEdit.getText().toString().trim();
userPassString = userPasswordEdit.getText().toString().trim();
if (!TextUtils.isEmpty(userEmailString) && !TextUtils.isEmpty(userPassString))
{
nAuth.createUserWithEmailAndPassword(userEmailString,userPassString).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
DatabaseReference mChildDatabase = mDatabaseRef.child("Users").push();
String key_user = mChildDatabase.getKey();
mChildDatabase.child("isVerified").setValue("unverified");
mChildDatabase.child("userKey").setValue(key_user);
mChildDatabase.child("emailUser").setValue(userEmailString);
mChildDatabase.child("passWordUser").setValue(userPassString);
Toast.makeText(MainActivity.this, "User Account Created!", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, Profile.class));
}
else
{
Log.w("TAG", "createUserWithEmail:failure",task.getException());
Toast.makeText(MainActivity.this, "User Account Creation Fail", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, MainActivity.class));
}
}
});
}
}
});
You should see warning in logcat:
I am stuck in a loop here.
Users can log in with their FB account. The app creates a Firebase user w/ the same info.
With the launcher activity (LoginActivity), if it detects an user is already logged in, it redirects them to their profile fragment.
However, on the profile fragment, I click the log off button and redirect
them to the Login page. This is where the cycle begins.
From code snippets and official Firebase doc, I am using .unauth();. However, my logcat still shows the user is logged in. I've also tried using the Facebook SDK method of LoginManager, but that hasn't worked either.
LogOut method (in MainFrag)
public void LogOut(){
Log.d(TAG, "CHECK #2: USER SIGNED OUT");
getActivity().getIntent().removeExtra("user_id");
getActivity().getIntent().removeExtra("profile_picture");
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
Log.d(TAG, "signed out" + mUser.getUid());
// mAuth.unauth();
Intent intent = new Intent(getActivity().getApplicationContext(),
LoginActivity.class);
myFirebaseRef.unauth();
LoginManager.getInstance().logOut();
startActivity(intent);
Log.d(TAG, "CHECK 3: FINISIHED SIGNED OUT");
Log.d(TAG, "onAuthStateChanged:signed_out");
}
LoginActivity
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "AndroidBash";
public User user;
private EditText email;
private EditText password;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private ProgressDialog mProgressDialog;
private DatabaseReference mDatabase;
//Add YOUR Firebase Reference URL instead of the following URL
private Firebase mRef=new Firebase("https://fitmaker-ee2c0.firebaseio.com/");
//FaceBook callbackManager
private CallbackManager callbackManager;
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "CHECK - FB SIGN IN - USER IS LOGGED IN " + mUser.getUid());
Intent intent = new Intent(getApplicationContext(), CustomColorActivity.class);
String uid = mAuth.getCurrentUser().getUid();
String image=mAuth.getCurrentUser().getPhotoUrl().toString();
intent.putExtra("user_id", uid);
if(image!=null || image!=""){
intent.putExtra("profile_picture",image);
}
startActivity(intent);
finish();
Log.d(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
}
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser mUser = firebaseAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
//FaceBook
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
signInWithFacebook(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
}
});
//
}
#Override
protected void onStart() {
super.onStart();
email = (EditText) findViewById(R.id.edit_text_email_id);
password = (EditText) findViewById(R.id.edit_text_password);
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
//FaceBook
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
//
protected void setUpUser() {
user = new User();
user.setEmail(email.getText().toString());
user.setPassword(password.getText().toString());
}
public void onSignUpClicked(View view) {
Intent intent = new Intent(this, SignUpActivity.class);
startActivity(intent);
}
public void onLoginClicked(View view) {
setUpUser();
signIn(email.getText().toString(), password.getText().toString());
}
private void signIn(String email, String password) {
Log.d(TAG, "signIn:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithEmail: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, "signInWithEmail", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
String uid = mAuth.getCurrentUser().getUid();
intent.putExtra("user_id", uid);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
//
}
private boolean validateForm() {
boolean valid = true;
String userEmail = email.getText().toString();
if (TextUtils.isEmpty(userEmail)) {
email.setError("Required.");
valid = false;
} else {
email.setError(null);
}
String userPassword = password.getText().toString();
if (TextUtils.isEmpty(userPassword)) {
password.setError("Required.");
valid = false;
} else {
password.setError(null);
}
return valid;
}
private void signInWithFacebook(AccessToken token) {
Log.d(TAG, "signInWithFacebook:" + token.getToken());
showProgressDialog();
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
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(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}else{
String uid=task.getResult().getUser().getUid();
String name=task.getResult().getUser().getDisplayName();
String email=task.getResult().getUser().getEmail();
String image=task.getResult().getUser().getPhotoUrl().toString();
//Create a new User and Save it in Firebase database
User user = new User(uid,name,null,email,name);
user = new User();
// user.setId(authData.getUid());
user.setName(name);
user.setEmail(email);
user.saveUser();
// mRef.child("uid").setValue(uid);
// mRef.child(name).setValue(user);
Log.d(TAG, uid);
Intent intent = new Intent(getApplicationContext(), CustomColorActivity.class);
intent.putExtra("user_id",uid);
intent.putExtra("profile_picture",image);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
MainFragment.java
public class MainFragment extends Fragment {
private static final String TAG = "AndroidBash";
public User user;
private Firebase myFirebaseRef =new Firebase("https://fitmaker-ee2c0.firebaseio.com/");
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private TextView name;
private TextView welcomeText;
private Button changeButton;
private Button revertButton;
private Button FBButton;
private ProgressDialog mProgressDialog;
// To hold Facebook profile picture
private ImageView profilePicture;
public MainFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container,
false);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
//((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
//Add YOUR Firebase Reference URL instead of the following URL
myFirebaseRef = new Firebase("https://fitmaker-ee2c0.firebaseio.com/");
mAuth = FirebaseAuth.getInstance();
name = (TextView) view.findViewById(R.id.text_view_name);
welcomeText = (TextView) view.findViewById(R.id.text_view_welcome);
changeButton = (Button) view.findViewById(R.id.button_change);
revertButton = (Button) view.findViewById(R.id.button_revert);
FBButton = (Button) view.findViewById(R.id.button_fb);
profilePicture = (ImageView) view.findViewById(R.id.profile_picture);
//Get the uid for the currently logged in User from intent data passed to this activity
String uid = getActivity().getIntent().getExtras().getString("user_id");
//Get the imageUrl for the currently logged in User from intent data passed to this activity
String imageUrl = getActivity().getIntent().getExtras().getString("profile_picture");
Log.d(TAG, "MainFrag - OnCreateView Check");
new ImageLoadTask(imageUrl, profilePicture).execute();
//Referring to the name of the User who has logged in currently and adding a valueChangeListener
myFirebaseRef.child(uid).child("name").addValueEventListener(new ValueEventListener() {
//onDataChange is called every time the name of the User changes in your Firebase Database
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Inside onDataChange we can get the data as an Object from the dataSnapshot
//getValue returns an Object. We can specify the type by passing the type expected as a parameter
String data = dataSnapshot.getValue(String.class);
name.setText("Hello " + data + ", ");
}
//onCancelled is called in case of any error
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getActivity().getApplicationContext(), "" + firebaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
//A firebase reference to the welcomeText can be created in following ways :
// You can use this :
//Firebase myAnotherFirebaseRefForWelcomeText=new Firebase("https://androidbashfirebaseupdat-bd094.firebaseio.com/welcomeText");*/
//OR as shown below
myFirebaseRef.child("welcomeText").addValueEventListener(new ValueEventListener() {
//onDataChange is called every time the data changes in your Firebase Database
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Inside onDataChange we can get the data as an Object from the dataSnapshot
//getValue returns an Object. We can specify the type by passing the type expected as a parameter
String data = dataSnapshot.getValue(String.class);
welcomeText.setText(data);
}
//onCancelled is called in case of any error
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getActivity().getApplicationContext(), "" + firebaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
//onClicking changeButton the value of the welcomeText in the Firebase database gets changed
changeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myFirebaseRef.child("welcomeText").setValue("Android App Development # AndroidBash");
}
});
FBButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// log user out
// add choice dialog later
LogOut();
}
});
//onClicking revertButton the value of the welcomeText in the Firebase database gets changed
revertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myFirebaseRef.child("welcomeText").setValue("Welcome to Learning # AndroidBash");
}
});
return view;
}
#Override
public void onResume() {
Log.d(TAG, "onResume of MainFragment");
CheckIfLoggedOut();;
super.onResume();
}
public void CheckIfLoggedOut() {
// here, check if user still logged in.
FirebaseUser mUser = mAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "MainFrag - Signed In (onResume)");
} else {
// User is signed out
Log.d(TAG, "check resume: starting log out for " + mUser.getUid());
LogOut();
}
}
public void LogOut(){
Log.d(TAG, "CHECK #2: USER SIGNED OUT");
getActivity().getIntent().removeExtra("user_id");
getActivity().getIntent().removeExtra("profile_picture");
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
Log.d(TAG, "signed out" + mUser.getUid());
// mAuth.unauth();
Intent intent = new Intent(getActivity().getApplicationContext(),
LoginActivity.class);
myFirebaseRef.unauth();
LoginManager.getInstance().logOut();
startActivity(intent);
Log.d(TAG, "CHECK 3: FINISIHED SIGNED OUT");
Log.d(TAG, "onAuthStateChanged:signed_out");
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(getContext());
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
FirebaseAuth.getInstance().signOut();
Adding this piece of line solved my problem.