dimanche 1 mars 2020

Android If statement not breaking when condition is true

In this activity I am creating an account for users. I am using mobsandgeeks.saripaar API for validation features. To allow the activity to work I currently print the errors to an invisible text field, if this textfield has text, the activity does not go onto the next activity (i.e. there is an issue with user input).

I am having a problem with the if statement that checks if the username or email already exists in the database. When condition is true (checked in logs), the account is not created, but the 'Account created' message is still displayed and the application still goes to the next activity.

Any help on this would be much appreciated. Thanks

CreateAccount.java

DatabaseHelper myDb;
private static final String TAG = "CreateAccount";
//http://learningprogramming.net/mobile/android/form-validation-in-android/
@NotEmpty
@Length(min = 3, max = 10)
private EditText etUsername;

@NotEmpty
private EditText etUserAddress;

@NotEmpty
private EditText etFirstName;

@NotEmpty
private EditText etLastName;

@NotEmpty
@Email
private EditText etEmail;

@NotEmpty
@Pattern(regex =  "(^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$)")
private EditText etPhone;

@NotEmpty
private EditText etPaypal;

//Valid = abcABC123!
@NotEmpty
@Password(scheme = Password.Scheme.ALPHA_NUMERIC_SYMBOLS)
private EditText etPassword;

@ConfirmPassword
EditText etConfirmPassword;
Button btnCreateAccount;

TextView check;

//https://www.youtube.com/watch?v=rt-8PgncIio
ImageView profileImageView;
Button btnProfilePic;
private static final int SELECT_PHOTO = 1;
private static final int CAPTURE_PHOTO = 2;
ProgressDialog progressBar;
int progressBarStatus;
Handler progressBarHandler = new Handler();
Bitmap thumbnail;

private Validator validator;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_account);

    myDb = new DatabaseHelper(this);

    validator = new Validator(this);
    validator.setValidationListener(this);

    etUsername = findViewById(R.id.etUsername);
    etFirstName = findViewById(R.id.etFirstName);
    etLastName = findViewById(R.id.etLastName);
    etUserAddress = findViewById(R.id.etAddress);
    etEmail = findViewById(R.id.etEmail);
    etPassword = findViewById(R.id.etPasswordLogin);
    etConfirmPassword = findViewById(R.id.etConfirmPasswordLogin);
    etPhone = findViewById(R.id.etPhoneNo);
    etPaypal = findViewById(R.id.etPaypalName);
    btnCreateAccount = findViewById(R.id.btnCreateAccount);
    check = findViewById(R.id.tvCheck);
    btnProfilePic = findViewById(R.id.btnProfilePicture);
    profileImageView = findViewById(R.id.imageProfile);

    btnProfilePic.setOnClickListener(this);

    //(https://www.youtube.com/watch?v=rt-8PgncIio) Image
    //had to change permissions in the Android Manifest file to allow for camera to be used
    if (ContextCompat.checkSelfPermission(CreateAccount.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        profileImageView.setEnabled(false);
        ActivityCompat.requestPermissions(CreateAccount.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
    } else {
        profileImageView.setEnabled(true);
    }
    createAccount();
}

public void createAccount() {

    btnCreateAccount.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            validator.validate();
            //(https://www.youtube.com/watch?v=rt-8PgncIio) Image
            profileImageView.setDrawingCacheEnabled(true);
            profileImageView.buildDrawingCache();
            Bitmap bitmap = profileImageView.getDrawingCache();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] data = baos.toByteArray();

            String email1 = etEmail.getText().toString().trim();
            Log.d(TAG, "onClick: email " + email1);
            String username = etUsername.getText().toString().trim();
            Log.d(TAG, "onClick: username " + username);
            boolean emailExists = myDb.checkIfEmailAlreadyExists(email1);
            Log.d(TAG, "onClick: emailExists " + emailExists);
            boolean usernameExists = myDb.checkIfUsernameAlreadyExists(username);
            Log.d(TAG, "onClick: usernameExists " + usernameExists);



            //https://stackoverflow.com/questions/6290531/check-if-edittext-is-empty
             if (etUsername.getText().toString().matches("") | etFirstName.getText().toString().matches("") | etLastName.getText().toString().matches("")
            | etEmail.getText().toString().matches("") | etUserAddress.getText().toString().matches("") | etPassword.getText().toString().matches("")|
                    etConfirmPassword.getText().toString().matches("") | etPhone.getText().toString().matches("") | etPaypal.getText().toString().matches(""))
            {
                Toast.makeText(CreateAccount.this, "Please fill empty fields", Toast.LENGTH_LONG).show();
            }

            else if(check.getText().toString().matches("") == false) {

                Toast.makeText(CreateAccount.this, "Please enter correct details", Toast.LENGTH_SHORT).show();
            }

            else {
                  if (usernameExists){
                     Log.d(TAG, "onClick: userExists " + usernameExists);
                     Toast.makeText(CreateAccount.this, "This username is already registered", Toast.LENGTH_LONG).show();
                     check.setText("TEXT");
                 }
                 else if (emailExists){
                     Log.d(TAG, "onClick: emailExists" + emailExists);
                     Toast.makeText(CreateAccount.this, "This email is already registered", Toast.LENGTH_LONG).show();
                     check.setText("TEXT");
                  }
                 else if (usernameExists == false | emailExists == false) {
                      boolean checktext = check.getText().equals("");

                              // original CRUD video - https://www.youtube.com/watch?v=kDZES1wtKUY&list=PLS1QulWo1RIaRdy16cOzBO5Jr6kEagA07&index=8
                              boolean isInserted = myDb.insertUserData(etUsername.getText().toString(), etUserAddress.getText().toString(), etFirstName.getText().toString(), etLastName.getText().toString(),
                                      etEmail.getText().toString(), etPassword.getText().toString(), etPhone.getText().toString(),
                                      etPaypal.getText().toString(), data);

                              if (isInserted == true) {
                                  if (checktext == true) {
                                      onValidationSucceeded();
                                  }
                                  else if (checktext == false){
                                      Toast.makeText(CreateAccount.this, "Account not Created", Toast.LENGTH_LONG).show();
                                  }
                                  }
                              } else {
                                  Toast.makeText(CreateAccount.this, "Account not Created", Toast.LENGTH_LONG).show();
                              }

                      }

            }

    });
}



//http://learningprogramming.net/mobile/android/form-validation-in-android/
@Override
public void onValidationFailed(List<ValidationError> errors) {
    for (ValidationError error : errors) {
        View view = error.getView();
        //TextView check = findViewById(R.id.tvCheck);
        String message = error.getCollatedErrorMessage(this);
        // Display error messages
        if (view instanceof EditText) {
            ((EditText) view).setError(message);
        } else {
            Toast.makeText(this, message, Toast.LENGTH_LONG).show();
        }
        check.setText(errors.toString());
    }
}

//http://learningprogramming.net/mobile/android/form-validation-in-android/
@Override
public void onValidationSucceeded() {
    Toast.makeText(CreateAccount.this, "Account Created, Please sign in", Toast.LENGTH_LONG).show();
    Intent intent = new Intent(CreateAccount.this, Login.class);
    startActivity(intent);
}

Aucun commentaire:

Enregistrer un commentaire