I have recently adopted Firebase for my Backend work. Using Firebase I want to store all the user data like username, phone number, etc to Firebase in the same RegisterActivity and not just Email & Password. How can I achieve this ?
My RegisterActivity will only appear at the time of installation. When user have register to my app, I am destroying the activity. So, there is no instance of RegisterActivity further.
RegisterActivity - onCreate():
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
setContentView(R.layout.activity_register);
initialization();
underlineText(); //Underlining Text in App
userObj = new User();
userObj.setName(NAME);
userObj.setEMAIL(EMAIL);
userObj.setPHONE(PHN);
animShake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake); //Animation
vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); //Vibration
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitForm(); //Registration Click Listener
}
});
skip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
skipRegistrationSection(); //Skip Click Listener
}
});
runAtInstallation();
}
submitform():
private void submitForm() {
if (!checkName()) {
name.setAnimation(animShake);
name.startAnimation(animShake);
vib.vibrate(60);
return;
}
if (!checkEmail()) {
email.setAnimation(animShake);
email.startAnimation(animShake);
vib.vibrate(60);
return;
}
if (!checkPhone()) {
phone.setAnimation(animShake);
phone.startAnimation(animShake);
vib.vibrate(60);
return;
}
if (!checkPassword()) {
password.setAnimation(animShake);
password.startAnimation(animShake);
vib.vibrate(60);
return;
}
if (!checkConfirmPassword()) {
confirmPassword.setAnimation(animShake);
confirmPassword.startAnimation(animShake);
vib.vibrate(60);
return;
}
nameLayout.setErrorEnabled(false);
emailLayout.setErrorEnabled(false);
phoneLayout.setErrorEnabled(false);
passwordLayout.setErrorEnabled(false);
confirmPasswordLayout.setErrorEnabled(false);
NAME = name.getText().toString().trim();
EMAIL = email.getText().toString().trim();
PHN = phone.getText().toString().trim();
PASSWORD = password.getText().toString();
progressBar.setVisibility(View.VISIBLE);
authUser(); //authenticating User via Email & Password
}
authUser():
private void authUser() {
mFirebaseAuth.createUserWithEmailAndPassword(EMAIL, PASSWORD).addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage(task.getException().getMessage())
.setTitle("Error")
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
progressBar.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.GONE);
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
});
}
runAtInstallation:
private void runAtInstallation() {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if (pref.getBoolean("activity_executed", false)) {
Intent act = new Intent(getApplicationContext(), MainActivity.class);
act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
act.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(act);
finish();
} else {
SharedPreferences.Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
}
I want to save name,email,& phone in the firebase database during registration and to destroy the activity after that.
I'm working on the same problem right now. The thing is, sign-IN (authentication) and sign-UP (registration) are two different things.
What I have done is have two separate activities, signIN... and signUP (register).
Once the user is signed up (email and password), they will have a unique userID known to Firebase.
Next, they go to the registration activity, so when you "upload" all the data from the editTexts in this activity, you can upload them to a node (key... index) in your database that matches the userID... so your data in your database looks like:
\ mydatabase \ users \ [uniqueID] \
If you combine both activies (authentication and registration) into one... with many fields, "email, password, name, phonenumber, etc." all in one activity, then you're going to still need to make a separate signIN only activity for the next time they run the app with an expired session. I think it's much simpler to do two separate activites.
I have one activity and I simply try to register right away regardless if the user exists or not and then if the error is due to the email existing already I sign the user in instead of registering them.
mAuth = FirebaseAuth.getInstance();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
if(task.getException() instanceof FirebaseAuthUserCollisionException) {
// login user
}
else {
// handle error
}
}
else {
// register user
}
}
You can add user profile information and other details like
For update profile
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName("Jane Q. User")
.setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg"))
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User profile updated.");
}
}
});
For more details to manage user details please refer this link Firebase manage user
Related
I'm currently working on a parental control application, what I would want to achieve is that the parent and child can login to the system with the same email address on different devices, and I also want to achieve auto login feature, when the parent open the app, it will directly load the ParentActivity, if child then load the ChildActivity.
But now the problem is that I can't do this, I have no idea how to identify both of them since they are using the same email address. Previously, I was able to perform auto login for the parent by using FirebaseAuth.getCurrentUser(), and then check the userType inside firestore. But now I can't check anything to identify whether the user is a child or parent.
What I have tried:
Create a field call "child", when the user (John) login as child, update the field with "TRUE" (let's say), when John quit app and login again, the system will starting checking if userType == "parents", if no then only it will check if child == "TRUE". Therefore, the child user will always be auto login to the ParentActivity but ChildActivity.
Is there any way to achieve this? Hope you guys understand what my problem is. The attached image shows how I achieve auto login for parent previously. Thanks in advance!
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Transparent Status Bar
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
ButterKnife.bind(this);
//FirebaseApp.initializeApp(this.getBaseContext());
firebaseAuth = FirebaseAuth.getInstance();
clearUserType();
}
// Hide keyboard after user clicking somewhere
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
#OnClick(R.id.LoginButton)
public void login(){
progressBar.setVisibility(View.VISIBLE);
if (!Utils.isValidEmail(email, emailLayout) | !Utils.hasEmail(email, emailLayout) | !Utils.hasPassword(password, passwordLayout)){
progressBar.setVisibility(View.INVISIBLE);
return;
}
startSignIn(email.getText().toString(), password.getText().toString());
}
#OnClick(R.id.SignUpButton)
public void signUpScreen(){
Intent signup = new Intent(this, SignUpActivity.class);
startActivity(signup);
finish();
}
#OnTextChanged(value = R.id.LoginEmailText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
public void emailChanged(CharSequence s){
if(!(s.length() < 1)){
emailLayout.setError(null);
}
}
#OnTextChanged(value = R.id.LoginPasswordText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
public void passwordChanged(CharSequence s){
if(!(s.length() < 1)){
passwordLayout.setError(null);
}
}
private void startSignIn(String email, String password){
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(task -> {
try {
if (task.isSuccessful()) {
updateUI();
}
else {
String error = task.getException().getMessage();
if (error.contains("There is no user record corresponding to this identifier. The user may have been deleted.") ||
error.contains("The password is invalid or the user does not have a password."))
{
Utils.ErrorSweetDialog(LoginActivity.this, "Login Failed", "Incorrect email or pasword. Please try again.",
"OK");
}
else if (error.contains("A network error (such as timeout, interrupted connection or unreachable host) has occurred.")){
Utils.ErrorSweetDialog(LoginActivity.this, "No Internet Connection",
"Please check your internet connection and try again.", "OK");
}
else
{
Utils.ErrorSweetDialog(LoginActivity.this, "Login Failed", error, "OK");
}
}
progressBar.setVisibility(View.INVISIBLE);
}
catch (Exception e){
Utils.ErrorSweetDialog(LoginActivity.this, "Oops! Something went wrong.",
"Sorry for the inconvenience. Please try again later.", "OK");
}
});
}
#Override
protected void onStart() {
super.onStart();
//clearUserType();
//FirebaseUser user = firebaseAuth.getCurrentUser();
/*DocumentReference docRef = db.collection("UserInfo").document(uid); //ZJkUy7J5UzTok7ioADAYqk77Opp1
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if(document.exists()){
String userType = document.getString("userType");
Log.e("LoginActivity",userType);
}
}
else{
}
}
});*/
/*if(user != null){
//updateUI();
String uid = firebaseAuth.getCurrentUser().getUid();
DocumentReference docRef = db.collection("UserInfo").document(uid); //ZJkUy7J5UzTok7ioADAYqk77Opp1
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if(document.exists()){
String userType = document.getString("userType");
Log.e("LoginActivity",userType);
if (userType.contains("parents")){
Log.e("contain parents", "yes");
Intent intent = new Intent(getApplicationContext(), ParentActivity.class);
startActivity(intent);
finish();
}
else{
}
}
}
else{
}
}
});
Intent intent = new Intent(this, ParentActivity.class);
startActivity(intent);
finish();
}
else{
Log.e("Login", "hi");
}*/
}
private void updateUI(){
Intent intent = new Intent(this, PickRoleActivity.class);
startActivity(intent);
finish();
}
private void clearUserType(){
FirebaseUser user = firebaseAuth.getCurrentUser();
//Log.e("urrent user", user.toString());
if(user != null){
progressBar.setVisibility(View.VISIBLE);
Log.e("user null: ", "no");
//updateUI();
String uid = firebaseAuth.getCurrentUser().getUid();
Log.e("UID: ",uid);
DocumentReference docRef = db.collection("UserInfo").document(uid); //ZJkUy7J5UzTok7ioADAYqk77Opp1
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if(document.exists()){
String userType = document.getString("userType");
String childStatus = document.getString("child");
Log.e("LoginActivity",userType);
if (userType.contains("parents")){
Log.e("contain parents", "yes");
progressBar.setVisibility(View.INVISIBLE);
Intent intent = new Intent(getApplicationContext(), ParentActivity.class);
startActivity(intent);
finish();
}
else if (childStatus.contains("TRUE")){
progressBar.setVisibility(View.INVISIBLE);
}
}
}
else{
Log.e("task unsuccessful:", " yes");
}
}
});
}
else{
Log.e("NULL: ", "No Such User.");
}
}
}
User account data in firestore
I assume you are enabling creation of multiple accounts with the same email address, which means the parent and the child have different passwords. With that, I suggest you take a look at Custom Claims. It basically give an account a 'tag' that you can access client side. Please notice that this will require you to write some Cloud Functions when creating accounts
EDIT: It's seem that you need a SharedPreferences. Here are the docs : developer.android.com/training/data-storage/shared-preferences . This way you can store a key like isParent:true in a SharedPreferences, and read its value everytime the app is started instead of saving it to Firestore.
You can check them at onCreate for Login Activity or if you have Splash Activity, you can check there.
DocumentReference docRef = db.collection("UserInfo").document(uid); //ZJkUy7J5UzTok7ioADAYqk77Opp1
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if(document.exists()){
String userType = document.getString("userType");
Log.e("LoginActivity",userType);
if (userType.equal("parents")){
Log.e("contain parents", "yes");
Intent intent = new Intent(getApplicationContext(), ParentActivity.class);
startActivity(intent);
finish();
}
else if (userType.equal("child")) {
//Here you missed, when child login
}
}
}
}
});
This question already has answers here:
Firebase kicks out current user
(19 answers)
Closed 3 years ago.
im devlop an app that has group admin, this group admin can join user by sign them with firebase, and after the admin sign them i want the app will sign back to the admin(the app could have multiple admin- one for each group),
i tried to save the currfirebase user and then switch back but when firebaseauth is change it change automaticlly the pervous user, i even make him final but it didt help
private final FirebaseUser currUser = currUserauth.getCurrentUser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
db = FirebaseFirestore.getInstance();
Button addContactBtn = findViewById(R.id.add_contact_btn);
progressBar = findViewById(R.id.add_content_progressbar);
userEmailEt = findViewById(R.id.et_email);
passwordEt = findViewById(R.id.et_password);
confirmBtnEt = findViewById(R.id.confirmBtn);
nameEt = findViewById(R.id.add_contact_name_et);
addContactBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addNewContact();
}
});
}
private void addNewContact() {
progressBar.setVisibility(View.VISIBLE);
final String email = userEmailEt.getText().toString();
String password = passwordEt.getText().toString().trim();
final String name = nameEt.getText().toString();
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches() || email.equals("")) {
userEmailEt.setError("Email is not valid");
} else if (TextUtils.isEmpty(password)) {
passwordEt.setError("password is not valid");
} else if(TextUtils.isEmpty(name)){
nameEt.setError("נא למלא שם");
}else {
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
FirebaseUser firebaseUser = mAuth.getCurrentUser();
Toast.makeText(getApplicationContext(), "User created successfully", Toast.LENGTH_SHORT).show();
update();
progressBar.setVisibility(View.GONE);
mAuth.signOut();
mAuth.updateCurrentUser(currUser).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
mAuth.getCurrentUser().reload().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Intent intent = new Intent(getApplicationContext(), ContactActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
System.out.println("From addContactActivity: " + mAuth.getCurrentUser().getEmail());
startActivity(intent);
finish();
}
});
User accounts can't create other user accounts in Firebase Authentication on the frontend. Also, only one user can be signed in at a time.
What you're trying to do is best suited to run on a backend you control, using the Firebase Admin SDK to create the user accounts.
I am creating a college application where i have put two section one for students and second for faculty.
Student and Faculty both are using authentication email and password method.
Problem is that when i login from student section and do minimize the application and then clear the task and reopen the app so app is starting from the beginning and if i am taping on faculty section so i am login there already even though i did not login by this section.
How to tackle this Problem?
mAuth.signInWithEmailAndPassword(user_email,user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
FirebaseUser authentic_user=mAuth.getCurrentUser();
if(authentic_user.isEmailVerified()) {
String user_id = mAuth.getCurrentUser().getUid();
database = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
email_check = dataSnapshot.child("email").getValue().toString();
} catch (NullPointerException error) {
email_check = null;
}
if (email_check != null) {
email.setText(email_check);
Intent intent = new Intent(getApplicationContext(), StudentDashboard.class);
startActivity(intent);
student_login_progress.setVisibility(View.INVISIBLE);
} else {
student_login_progress.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG).show();
FirebaseAuth.getInstance().signOut();
finish();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}else
{
startActivity(new Intent(getApplicationContext(),Student_Email_Verification.class));
student_login_progress.setVisibility(View.INVISIBLE);
}
}else
{
Toast.makeText(Login_Student.this,task.getException().getMessage(),Toast.LENGTH_LONG).show();
student_login_progress.setVisibility(View.GONE);
}
}
});
The problem is really simply before going to faculty Section check if you are logged in already.
if yes then try
FirebaseAuth.getInstance().signOut();
This will help you out to log out from existing account and login again with another faculty account.
I want to do a login screen that appears only if the user hasn't already logged in. I want to see a working example because I'm getting an error that I don't know how to fix
Attempt to invoke interface method 'void com.google.firebase.auth.FirebaseAuth$AuthStateListener.onAuthStateChanged(com.google.firebase.auth.FirebaseAuth)' on a null object reference
I want a NoDisplay activity to choose if opening the login or main activity. The login screen should have the option to login with email or google. If logging with the google email it should result in the same account as pressing the google sign-in button. The main activity should have a logout button and when pressed it should let the user select a different account in the logging screen.
Please go through these codes.
this code is used for user registration for the first time
mAuth = FirebaseAuth.getInstance();
username=(TextInputEditText)findViewById(R.id.rgusername);
Email=(TextInputEditText)findViewById(R.id.rgemail);
Password=(TextInputEditText)findViewById(R.id.rgpassword);
ok=(Button)findViewById(R.id.regibutton);
mprogress=new ProgressDialog(this);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Name=username.getText().toString();
String email=Email.getText().toString();
String pass=Password.getText().toString();
if (TextUtils.isEmpty(Name) || TextUtils.isEmpty(email) ||TextUtils.isEmpty(pass))
{
Toast.makeText(RegisterActivity.this, "Please Fill All the Filds", Toast.LENGTH_SHORT).show();
}
else
{
mprogress.setTitle("Register");
mprogress.setMessage("Please Wait While We Create Your Account");
mprogress.setCanceledOnTouchOutside(false);
mprogress.show();
registration(Name,email,pass);
}
}
});
}
private void registration(String name, String email, String pass) {
mAuth.createUserWithEmailAndPassword(email, pass)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
mprogress.dismiss();
Intent main=new Intent(RegisterActivity.this,MainActivity.class);
main.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(main);
finish();
} else {
mprogress.dismiss();
Toast.makeText(RegisterActivity.this, "Oop's Error occor", Toast.LENGTH_SHORT).show();
}
}
});
}
--------------------------------------------------------------------------------
This code check if the user is loged in or not
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser==null)
{
gotostart();
}
}
private void gotostart() {
Intent start=new Intent(MainActivity.this,StartActivity.class);
startActivity(start);
finish();
}
I'm trying to update my android code in the new Firebase after May 2016's update, but am running into issues. Previously my user create worked fine with
Firebase ref = new Firebase("https://project.firebaseio.com");
ref.createUser(email, password, new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result) {
System.out.println("Successfully created user account with uid: " + result.get("uid"));
error.setText("Account successfully created.");
}
#Override
public void onError(FirebaseError firebaseError) {
error.setText("Error with account creation");
}
});
but with the new system where I'm told I need to implement the system here: https://firebase.google.com/docs/auth/android/password-auth, I'm getting error
Cannot resolve method AddOnCompleteListener
whenever I try to put the method inside of an Android clickListener (how I'm sending the login data)
My (relevant) code is
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseAuth.AuthStateListener mAuthListener;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_login);
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
//Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
// Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
mCreateNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.email);
String email = editText.getText().toString();
editText = (EditText) findViewById(R.id.password);
String password = editText.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(logStr, "createUserWithEmail: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()) {
Toast.makeText(getApplicationContext(), "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.email);
String email = editText.getText().toString();
editText = (EditText) findViewById(R.id.password);
String password = editText.getText().toString();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(logStr, "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(logStr, "signInWithEmail", task.getException());
Toast.makeText(getApplicationContext(), "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
});
Reading through the new Firebase guide, it mentions that these new listeners wait for an update on the user's "sign in state" but doesn't really go into detail on that. How do I make it so that I can call the sign-in/create-new only when I click the buttons?
I know that taking the code outside of the clicklistener "solves" the problem, but then I don't know how to be able to control when the user sends login data.
I found a similar question that answers mine Firebase 9.0.0 mAuth.signInWithEmailAndPassword, how to pass it to a button
It seems that this issue is common enough that it necessitates more clarification on the Firebase site. Basically, .addOnCompleteListener() needs to be declared as it's own class within the login activity.
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {