Identify two users with the same email address - android

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
}
}
}
}
});

Related

checking if a user is in a specific child for login firebase

I am making an android application using Firebase database and I want to check that the user is not in registered as an "Association" so I am checking if he belongs to the child "Association".
The method userLogin is supposed to not log in the user if he is under the child "Associations" and log in him otherwise.
However, it is not working and the user is logged in even if he is under "Associations"
private void userLogin() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
String RegisteredUserID = currentUser.getUid();
DatabaseReference jLoginDatabase = FirebaseDatabase.getInstance().getReference().child("Associations").child(RegisteredUserID);
jLoginDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(), "You are not registered", Toast.LENGTH_SHORT).show();
}
else
{
finish();
Intent intent = new Intent(SignInDonor.this, homedonor.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}});}
else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
I did not tried this, but it should work, first, after you log in with a user and enters inside task.isSuccessful , you can retrieve the current logged in user with task.getResult().getUser().getUid(). Then just loop inside Associations and get each user key (I assume that Associations has userIDs inside as nodes with a certain value), then compare if the current logged in user is equal to one inside that node, if matchs it will pop up your Toast, if not you will be redirected.
Try this
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
DatabaseReference jLoginDatabase = FirebaseDatabase.getInstance().getReference().child("Associations");
jLoginDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(snapshot.getKey().equals(task.getResult().getUser().getUid()) {
Toast.makeText(getApplicationContext(), "You are not registered", Toast.LENGTH_SHORT).show();
}
else
{
finish();
Intent intent = new Intent(SignInDonor.this, homedonor.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
I used addListenerForSingleValueEvent because we only need to loop once at the reference and not keep listening for data

How to use two singin and singup methods of firebase in single android project

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.

Firebase User Verification Email

I am using Firebase as the Backend for an Mobile Android Application. When a User registers, I would like to have a verification email sent to that user.
When the User Clicks the "SignUp" button, the following logic is run through: First of all a number of variables are set from the filled in boxes. Then a few checks are performed on validity of the filled in parameters. If the checks are passed, a user is created in the Database. This is all functioning..
Then I would like to send a verification email to the user to check if the email is valid. I have also put this in the onClick method of the Button but this is not functioning yet.
I do not receive the verification email.
What is the reason behind this and the fix?
My onCreate Method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_sign_up_page);
setFontType();
screen = (EditText)findViewById(R.id.SchermNaam);
mail = (EditText)findViewById(R.id.EmailAdres);
knop = (Button)findViewById(R.id.SignUp_Button_SignUp);
firebaseAuth = FirebaseAuth.getInstance();
}
The onClick method for the "SignUp" Button:
public void onClickSignUpPage(View view){
String schermnaam = screen.getText().toString().trim();
String emailadres = mail.getText().toString().trim();
String paswoord = pass.getText().toString().trim();
if(TextUtils.isEmpty(schermnaam)){
Toast.makeText(this,"Schermnaam invullen", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(emailadres)){
Toast.makeText(this,"Email invullen",Toast.LENGTH_SHORT).show();
return;
}
if(!schermnaam_ok(schermnaam)){
Toast.makeText(this,"schermnaam minstens 5 en maximum 15 tekens", Toast.LENGTH_SHORT).show();
return;
}
if(!paswoord_ok(paswoord)){
Toast.makeText(this,"paswoord tussen 6-12 karakters en minstens 1 cijfer", Toast.LENGTH_SHORT).show();
return;
}
firebaseAuth.createUserWithEmailAndPassword(emailadres.trim(),paswoord)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(SignUpPage.this, "Nieuwe Speler Geregistreerd", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SignUpPage.this, SignInPage.class);
startActivity(intent);
}
else {
FirebaseAuthException e = (FirebaseAuthException) task.getException();
Toast.makeText(SignUpPage.this,"Fout in de SignUp"+e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("LoginActivity", "Failed Registration", e);
return;
}
}
});
FirebaseUser user = firebaseAuth.getCurrentUser();
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email sent.");
}
}
});
}
Changed it up to a sequential procedure, as suggested by the post quoted by #cramopy. Thank you for this!
Now you first need to "Sign Up" as a user, and then verify in another step, through another button. Then I receive the confirmation email.
Here my code for the onClick method for the 2 Buttons.. From a UX point of view, need to look at how to position the buttons. This is a functional viewpoint.
public void onClickSignUpPage(View view){
String schermnaam = screen.getText().toString().trim();
String emailadres = mail.getText().toString().trim();
String paswoord = pass.getText().toString().trim();
if(TextUtils.isEmpty(schermnaam)){
Toast.makeText(this,"Schermnaam invullen", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(emailadres)){
Toast.makeText(this,"Email invullen",Toast.LENGTH_SHORT).show();
return;
}
if(!schermnaam_ok(schermnaam)){
Toast.makeText(this,"schermnaam minstens 5 en maximum 15 tekens", Toast.LENGTH_SHORT).show();
return;
}
if(!paswoord_ok(paswoord)){
Toast.makeText(this,"paswoord tussen 6-12 karakters en minstens 1 cijfer", Toast.LENGTH_SHORT).show();
return;
}
firebaseAuth.createUserWithEmailAndPassword(emailadres.trim(),paswoord)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(SignUpPage.this, "Nieuwe Speler Geregistreerd", Toast.LENGTH_SHORT).show();
}
else {
FirebaseAuthException e = (FirebaseAuthException) task.getException();
Toast.makeText(SignUpPage.this,"Fout in de SignUp"+e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("LoginActivity", "Failed Registration", e);
return;
}
}
});
AddDataFireBase();
}
public void onClickVerify(View view){
FirebaseUser user = firebaseAuth.getCurrentUser();
assert user != null;
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email sent.");
}
else {
Log.e(TAG, "sendEmailVerification", task.getException());
Toast.makeText(SignUpPage.this,
"Failed to send verification email.",
Toast.LENGTH_SHORT).show();
}}
});
Intent intent = new Intent(SignUpPage.this, SignInPage.class);
startActivity(intent);
}
Your code should work. But I suggest you to follow the next steps to verify the email:
Create account
Check if creation was successful
Check if the email is verified with user.isEmailVerified()
Reload your user to update the instance with user.reload(). You should do this because some methods on Firebase ask you to reload or reauthenticate the user before realize some operations. Reload in this case will update the cache and data of your user.
Send the email using sendEmailVerification()
Something like:
authInstance.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (it.isSuccessful) {
//Create accountData in the database
if (it.result!!.user.isEmailVerified) {
it.result!!.user.reload()
.addOnCompleteListener {
if (it.isSuccessful) {
authInstance.currentUser!!.sendEmailVerification()
.addOnCompleteListener {
Log.i("TAG", "Yay! verificationSent")
}
} else {
//Manage error
}
}
}
} else {
//Manage error
}
}
Also, you should know that sometimes the email verification takes some time in Debug environments(at least from my experience I have saw delays of 1-3 minutes, but never on release versions).
Finally, before call user.verify() you should need to call again user.reload() to update the data of your user in the Firebase Cache, if not, even if you have click on Verify my email on the email sent to your account, the FirebaseAuthor.currentUser().isEmailVerified() will continue returning you false.

Verified user with Firebase

I want to create a login where the user only has to put his/her mail address and verify it via email. Using firebase I have this code so far:
When the user clicks the button to login after putting the mail in the field. I try to create a new account (password is random as I don't need it). If it doesn't exists I send a verification mail. If the account exists I check with checkIfVerifiedUser if the user verified the account by clicking the mail or not.
firebaseAuth.createUserWithEmailAndPassword(email, Math.random() + "").addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = firebaseAuth.getCurrentUser();
user.sendEmailVerification().addOnCompleteListener((Activity) context, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(context, "we sent a mail, please verify", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "error", Toast.LENGTH_LONG).show();
}
}
});
checkIfVerifiedUser(email);
} else {
progressDialog.dismiss();
try {
throw task.getException();
} catch (FirebaseAuthUserCollisionException e) {
// In case the account already exists
checkIfVerifiedUser(email);
} catch (Exception e) {
Toast.makeText(context, R.string.error_auth, Toast.LENGTH_SHORT).show();
}
}
} });
Here is the method I call:
private void checkIfVerifiedUser(String email){
final FirebaseUser user = firebaseAuth.getCurrentUser();
Intent intent = new Intent(context, HomeActivity.class);
if(user != null){
user.reload();
// If the user is created, we check if the account is verified
if(user.isEmailVerified()) {
intent.putExtra(IntentEnum.ALREADYREGISTERED.getCode(), true);
}else{
intent.putExtra(IntentEnum.ALREADYREGISTERED.getCode(), false);
}
}else{
intent.putExtra(IntentEnum.ALREADYREGISTERED.getCode(), false);
}
---rest of code---
}
The problem is that I either get firebaseAuth.getCurrentUser() == null or user.isEmailVerified() always false (even if I click the link in the email I get sent).
Could anyone help me with this?
Thanks!
To solve this, you need to call checkIfVerifiedUser() method inside onComplete() method and inside the if statement.
Hope it helps.

Firebase Realtime Database & Auth

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

Categories

Resources