Checking if emailis in database, otherwise store username and password in database

I am trying to run through a method (register();) which checks if the fields in a register page are empty. After I want to check if an email is store in the SQLite database and if it is not, store the email and password in the database. The following is my code:

Database (user methods)

 public boolean insertUser(UserModel userModel)
{
    String password;
    password = getSecurePassword(userModel.getPassword(),    "Easy Pill");
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put("FIRSTNAME", userModel.getFirstName());
    values.put("LASTNAME", userModel.getLastName());
    values.put("EMAIL", userModel.getEmail());
    values.put("AGE", userModel.getAge());
    values.put("PASSWORD", password);
    long result  = db.insert(TABLE_USER, null, values );
    if(result == -1)
        return false;
    else
        return true;

}

public boolean insertUserData(String email, String password){
    ContentValues contentValues = new ContentValues();
    contentValues.put("EMAIL", email);
    contentValues.put("PASSWORD", password);
    long result  = db.insert("USER", null, contentValues );
    if(result == -1)
        return false;
    else
        return true;
}

public Boolean getLoginInfo(UserModel user){
    SQLiteDatabase db = this.getReadableDatabase();
    String password;
    password= getSecurePassword(user.getPassword(),    "Easy Pill");
    String query = "Select EMAIL, PASSWORD FROM " + TABLE_USER + " WHERE EMAIL = '"+user.getEmail() +"' AND PASSWORD= '"+password+"'";
    Cursor resultSet = db.rawQuery(query, null);
    if(resultSet.getCount()== 0)
        return false;
    else
        return true;
    //resultSet.close();
}
}

Register Activity

public class RegisterActivityController extends AppCompatActivity {
private EditText firstName, lastName, dateOfBirth, email, password, confirmPassword;
private String first, last, birth, emailAdd, passwd, conPasswd;
Calendar myCalendar = Calendar.getInstance();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    firstName = findViewById(R.id.firstName);
    lastName = findViewById(R.id.lastName);
    dateOfBirth = findViewById(R.id.dateOfBirth);
    email = findViewById(R.id.email);
    password = findViewById(R.id.password);
    confirmPassword = findViewById(R.id.confirmPassword);
    Button createButton = findViewById(R.id.createButton);
    createButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            register();
        }
    });

    final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateLabel();
        }

    };

    dateOfBirth.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new DatePickerDialog(RegisterActivityController.this, date, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH)).show();
        }
    });
}

private void updateLabel() {
    String myFormat = "MM/dd/yy";
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
    dateOfBirth.setText(sdf.format(myCalendar.getTime()));
}

public void register() {
    initialize();
    if (!validate()) {
        Toast.makeText(this, "Failed to create account.", Toast.LENGTH_SHORT).show();
    } else {
        onSignupSuccess();
    }
}

public void initialize() {
    first = firstName.getText().toString().trim();
    last = lastName.getText().toString().trim();
    birth = dateOfBirth.getText().toString().trim();
    emailAdd = email.getText().toString().trim();
    passwd = password.getText().toString().trim();
    conPasswd = confirmPassword.getText().toString().trim();
}

public boolean validate() {
    boolean valid = true;
    if (firstName.length() == 0 || firstName.length() > 32) {
        firstName.setError("Please enter a valid first name.");
        valid = false;
    }
    if (lastName.length() == 0 || lastName.length() > 32) {
        lastName.setError("Please enter a valid last name.");
        valid = false;
    }
    if (dateOfBirth.length() == 0 || TextUtils.isEmpty(dateOfBirth.getText().toString())) {
        dateOfBirth.setError("Please enter your date of birth.");
        valid = false;
    }
    if (email.length() == 0 || !Patterns.EMAIL_ADDRESS.matcher(emailAdd).matches()) {
        email.setError("Please enter a valid Email Address.");
        valid = false;
    }
    if (password.length() == 0) {
        password.setError("Please enter password.");
        valid = false;
    }
    if (confirmPassword.length() == 0 || !passwd.equals(conPasswd)) {
        confirmPassword.setError("Please reenter password or make sure passwords match.");
        valid = false;
    }
    return valid;
}

public void onSignupSuccess() {
    Toast.makeText(getBaseContext(), "User account: " + first + " " + last + ", created.", Toast.LENGTH_SHORT).show();
}
}

Register.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".login.activity.controllers.RegisterActivityController">


    <EditText
        android:id="@+id/firstName"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="@string/first_name"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/lastName"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="@string/last_name"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/firstName" />

    <EditText
        android:id="@+id/dateOfBirth"
        android:clickable="true"
        android:focusable="false"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="@string/date_of_birth"
        android:inputType="date"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/lastName" />

    <EditText
        android:id="@+id/email"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="@string/add_email"
        android:inputType="textEmailAddress"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/dateOfBirth" />

    <EditText
        android:id="@+id/password"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="@string/add_password"
        android:inputType="textPassword"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/email" />

    <EditText
        android:id="@+id/confirmPassword"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="@string/confirm_password"
        android:inputType="textPassword"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/password" />

    <Button
        android:id="@+id/createButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="148dp"
        android:layout_marginStart="148dp"
        android:layout_marginTop="24dp"
        android:text="@string/create_account"
        android:onClick="touchRegisterUser"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/confirmPassword" />

</android.support.constraint.ConstraintLayout>
</ScrollView>

I've done a ton of research on this and tried a few different things, but I need to run the register method in the Register activity and if that comes back all good then I need to check the email and password and then store them both. Any and all help would be appreciated.

1 answer

  • answered 2018-04-14 20:50 MikeT

    First you could add the following method to your Database(user methods) class:-

    public boolean isEmailUnique(String email) {
        int count=0;
        String whereclause = "EMAIL=?";
        String[] whereargs = new String[]{email};
        Cursor csr =db.query("USER",null,whereclause,whereargs,null,null,null);
        count = csr.getCount();
        csr.close();
        return count < 1;
    }
    

    Then you could include a check, at the appropriate place in the register method, along the lines of

    if (!db.isEmailUnique(emailAdd)) 
    {
        email.setError("Please enter a Unique Email Address.");   
        valid = false;
    }
    

    Alternately you could alter :-

    if (email.length() == 0 || !Patterns.EMAIL_ADDRESS.matcher(emailAdd).matches()) {
        email.setError("Please enter a valid Email Address.");
        valid = false;
    }
    

    To be :-

    if (email.length() == 0 || !Patterns.EMAIL_ADDRESS.matcher(emailAdd).matches() || !db.isEmailUnique(emailAdd)) {
        email.setError("Please enter a valid Email Address.");
        valid = false;
    }
    

    Additional

    It also appears that you are not invoking the insertUser method to actually add the user.

    I'd suggest the following change to the register mnethod :-

    public void register() {
        initialize();
        if (!validate()) {
            Toast.makeText(this, "Failed to create account.", Toast.LENGTH_SHORT).show();
        } else {
            If (db.insertUser(emailAdd,passwd)) {
                onSignupSuccess();
            } else {
                Toast.makeText(this, "Failed to create account (insert into database did not insert a row.).", Toast.LENGTH_SHORT).show();
            }
        }
    }