Search in sources :

Example 1 with UserProfileChangeRequest

use of com.google.firebase.auth.UserProfileChangeRequest in project FirebaseAuth-Android by jirawatee.

the class ManageUserActivity method updateNameAndPhoto.

private void updateNameAndPhoto(FirebaseUser user) {
    showProgressDialog();
    UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder().setDisplayName(mEditTextName.getText().toString()).setPhotoUri(Uri.parse(mEditTextPhoto.getText().toString())).build();
    user.updateProfile(profileUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {

        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                mTextViewProfile.setTextColor(Color.DKGRAY);
                mTextViewProfile.setText(getString(R.string.updated, "User profile"));
            } else {
                mTextViewProfile.setTextColor(Color.RED);
                mTextViewProfile.setText(task.getException().getMessage());
            }
            hideProgressDialog();
        }
    });
}
Also used : UserProfileChangeRequest(com.google.firebase.auth.UserProfileChangeRequest)

Example 2 with UserProfileChangeRequest

use of com.google.firebase.auth.UserProfileChangeRequest in project FirebaseUI-Android by firebase.

the class RegisterEmailFragment method registerUser.

private void registerUser(final String email, final String name, final String password) {
    mHelper.getFirebaseAuth().createUserWithEmailAndPassword(email, password).addOnFailureListener(new TaskFailureLogger(TAG, "Error creating user")).addOnSuccessListener(new OnSuccessListener<AuthResult>() {

        @Override
        public void onSuccess(AuthResult authResult) {
            // Set display name
            UserProfileChangeRequest changeNameRequest = new UserProfileChangeRequest.Builder().setDisplayName(name).setPhotoUri(mUser.getPhotoUri()).build();
            final FirebaseUser user = authResult.getUser();
            user.updateProfile(changeNameRequest).addOnFailureListener(new TaskFailureLogger(TAG, "Error setting display name")).addOnCompleteListener(new OnCompleteListener<Void>() {

                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    // This executes even if the name change fails, since
                    // the account creation succeeded and we want to save
                    // the credential to SmartLock (if enabled).
                    mHelper.saveCredentialsOrFinish(mSaveSmartLock, getActivity(), user, password, new IdpResponse(EmailAuthProvider.PROVIDER_ID, email));
                }
            });
        }
    }).addOnFailureListener(getActivity(), new OnFailureListener() {

        @Override
        public void onFailure(@NonNull Exception e) {
            mHelper.dismissDialog();
            if (e instanceof FirebaseAuthWeakPasswordException) {
                // Password too weak
                mPasswordInput.setError(getResources().getQuantityString(R.plurals.error_weak_password, R.integer.min_password_length));
            } else if (e instanceof FirebaseAuthInvalidCredentialsException) {
                // Email address is malformed
                mEmailInput.setError(getString(R.string.invalid_email_address));
            } else if (e instanceof FirebaseAuthUserCollisionException) {
                // Collision with existing user email, it should be very hard for
                // the user to even get to this error due to CheckEmailFragment.
                mEmailInput.setError(getString(R.string.error_user_collision));
            } else {
                // General error message, this branch should not be invoked but
                // covers future API changes
                mEmailInput.setError(getString(R.string.email_account_creation_error));
            }
        }
    });
}
Also used : TaskFailureLogger(com.firebase.ui.auth.ui.TaskFailureLogger) FirebaseAuthWeakPasswordException(com.google.firebase.auth.FirebaseAuthWeakPasswordException) UserProfileChangeRequest(com.google.firebase.auth.UserProfileChangeRequest) AuthResult(com.google.firebase.auth.AuthResult) FirebaseUser(com.google.firebase.auth.FirebaseUser) FirebaseAuthWeakPasswordException(com.google.firebase.auth.FirebaseAuthWeakPasswordException) FirebaseAuthInvalidCredentialsException(com.google.firebase.auth.FirebaseAuthInvalidCredentialsException) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) FirebaseAuthInvalidCredentialsException(com.google.firebase.auth.FirebaseAuthInvalidCredentialsException) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) IdpResponse(com.firebase.ui.auth.IdpResponse)

Example 3 with UserProfileChangeRequest

use of com.google.firebase.auth.UserProfileChangeRequest in project Quizly by sebastianjs12.

the class CreateStudentAccount method clickStudentCreateSubmit.

// add username and password, create account **waitfor database
public void clickStudentCreateSubmit(View v) {
    if (v.getId() == R.id.studentCreateSubmitButton) {
        // gather username and password and store to strings
        EditText us = (EditText) findViewById(R.id.teacherUsernameText);
        String usernameStr = us.getText().toString();
        EditText pw = (EditText) findViewById(R.id.teacherPasswordText);
        String passwordStr = pw.getText().toString();
        if (TextUtils.isEmpty(usernameStr)) {
            Toast.makeText(this, "Username is empty try again", Toast.LENGTH_LONG).show();
            return;
        }
        if (TextUtils.isEmpty(passwordStr)) {
            Toast.makeText(this, "Password is empty try again", Toast.LENGTH_LONG).show();
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        firebaseAuth.createUserWithEmailAndPassword(usernameStr, passwordStr).addOnCompleteListener(CreateStudentAccount.this, new OnCompleteListener<AuthResult>() {

            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(CreateStudentAccount.this, "Registered Successfully", Toast.LENGTH_SHORT).show();
                    finish();
                    UserProfileChangeRequest setUserType = new UserProfileChangeRequest.Builder().setDisplayName("student").build();
                    Intent i = new Intent(CreateStudentAccount.this, StudentLogin.class);
                    startActivity(i);
                } else {
                    Toast.makeText(CreateStudentAccount.this, "Registered Unsuccessfully, try again", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
Also used : EditText(android.widget.EditText) UserProfileChangeRequest(com.google.firebase.auth.UserProfileChangeRequest) AuthResult(com.google.firebase.auth.AuthResult) Intent(android.content.Intent)

Example 4 with UserProfileChangeRequest

use of com.google.firebase.auth.UserProfileChangeRequest in project ShelterApp by farzamtn.

the class RegistrationActivity method newRegistration.

/**
 * Button event handler for the register button - uses FireBase email/password authentication
 * to validate the email and password entered by user.
 *
 * @param view the current view
 */
public void newRegistration(View view) {
    // Reset errors.
    email.setError(null);
    password.setError(null);
    final String fullName = name.getText().toString();
    final String user = email.getText().toString().trim();
    final String pass = password.getText().toString().trim();
    final String phoneNum = phoneNumber.getText().toString().trim();
    // Retrieving the selected user type
    int selectedButtonId = userTypes.getCheckedRadioButtonId();
    RadioButton selectedUser = findViewById(selectedButtonId);
    final String userType = selectedUser.getText().toString();
    boolean cancel = false;
    View focusView = null;
    if (TextUtils.isEmpty(phoneNum)) {
        phoneNumber.setError(getString(R.string.error_field_required));
        focusView = phoneNumber;
        cancel = true;
    } else if (!Registration.isPhoneNumberValid(phoneNum)) {
        phoneNumber.setError(getString(R.string.error_invalid_phoneNumber));
        focusView = phoneNumber;
        cancel = true;
    }
    if (TextUtils.isEmpty(pass)) {
        password.setError(getString(R.string.error_field_required));
        focusView = password;
        cancel = true;
    } else if (Login.isPasswordValid(pass)) {
        password.setError(getString(R.string.error_minimum_password));
        focusView = password;
        cancel = true;
    }
    if (TextUtils.isEmpty(user)) {
        this.email.setError(getString(R.string.error_field_required));
        focusView = email;
        cancel = true;
    } else if (Login.isUsernameValid(user)) {
        email.setError(getString(R.string.error_invalid_email));
        focusView = email;
        cancel = true;
    }
    if (TextUtils.isEmpty(fullName)) {
        name.setError(getString(R.string.error_field_required));
        focusView = name;
        cancel = true;
    } else if (!Registration.isNameValid(fullName)) {
        name.setError(getString(R.string.error_invalid_name));
        focusView = password;
        cancel = true;
    }
    if (cancel) {
        // There was an error; don't attempt registration and ask for focus.
        focusView.requestFocus();
    } else {
        // Show a progress spinner, and kick off a background task to
        // perform the new user registration attempt.
        progressBar.setVisibility(View.VISIBLE);
        // create user using FireBase email/password authentication server
        mAuth.createUserWithEmailAndPassword(user, pass).addOnCompleteListener(RegistrationActivity.this, task -> {
            progressBar.setVisibility(View.GONE);
            // signed in user can be handled in the listener.
            if (!task.isSuccessful()) {
                Toast.makeText(RegistrationActivity.this, "Authentication failed." + task.getException(), Toast.LENGTH_LONG).show();
            } else {
                if (mAuth.getCurrentUser() != null) {
                    UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder().setDisplayName(fullName).build();
                    // Updating user name
                    mAuth.getCurrentUser().updateProfile(profileUpdates).addOnCompleteListener(task1 -> {
                        if (!task1.isSuccessful()) {
                            Log.d("Update profile error", Objects.requireNonNull(task.getException()).toString());
                        }
                    });
                    // Updating user email
                    mAuth.getCurrentUser().updateEmail(user).addOnCompleteListener(task12 -> {
                        if (!task.isSuccessful()) {
                            Log.d("Update Email error", Objects.requireNonNull(task.getException()).toString());
                        }
                    });
                    // Adding new user information to DB with Uid being their Unique Key
                    String user_id = mAuth.getCurrentUser().getUid();
                    DatabaseReference current_user_db = mRegisterDatabase.child(user_id);
                    current_user_db.child("Name").setValue(fullName);
                    current_user_db.child("Email").setValue(user);
                    current_user_db.child("Phone Number").setValue(phoneNum);
                    current_user_db.child("User Type").setValue(userType);
                    current_user_db.child("Checked In").setValue(-1);
                    current_user_db.child("Beds").setValue(0);
                    current_user_db.child("Disabled").setValue("false");
                }
                Toast.makeText(RegistrationActivity.this, "Your new account has been created. Welcome!", Toast.LENGTH_LONG).show();
                // Start the correct activity based on user type
                switch(userType) {
                    case "Admin":
                        startActivity(new Intent(RegistrationActivity.this, AdminActivity.class));
                        break;
                    case "Shelter Employee":
                        sendVerificationEmail();
                        startActivity(new Intent(RegistrationActivity.this, LoginActivity.class));
                        finish();
                        break;
                    case "Shelter Seeker":
                        sendVerificationEmail();
                        startActivity(new Intent(RegistrationActivity.this, LoginActivity.class));
                        finish();
                        break;
                }
            }
        });
    }
}
Also used : DatabaseReference(com.google.firebase.database.DatabaseReference) UserProfileChangeRequest(com.google.firebase.auth.UserProfileChangeRequest) Intent(android.content.Intent) RadioButton(android.widget.RadioButton) View(android.view.View)

Aggregations

UserProfileChangeRequest (com.google.firebase.auth.UserProfileChangeRequest)4 Intent (android.content.Intent)2 AuthResult (com.google.firebase.auth.AuthResult)2 View (android.view.View)1 EditText (android.widget.EditText)1 RadioButton (android.widget.RadioButton)1 IdpResponse (com.firebase.ui.auth.IdpResponse)1 TaskFailureLogger (com.firebase.ui.auth.ui.TaskFailureLogger)1 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)1 OnSuccessListener (com.google.android.gms.tasks.OnSuccessListener)1 FirebaseAuthInvalidCredentialsException (com.google.firebase.auth.FirebaseAuthInvalidCredentialsException)1 FirebaseAuthUserCollisionException (com.google.firebase.auth.FirebaseAuthUserCollisionException)1 FirebaseAuthWeakPasswordException (com.google.firebase.auth.FirebaseAuthWeakPasswordException)1 FirebaseUser (com.google.firebase.auth.FirebaseUser)1 DatabaseReference (com.google.firebase.database.DatabaseReference)1