关于java:检查电子邮件是否在数据库中,否则将用户名和密码存储在数据库中

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

我正在尝试通过一个方法 (register();) 检查注册页面中的字段是否为空。在我想检查电子邮件是否存储在 SQLite 数据库中之后,如果没有,请将电子邮件和密码存储在数据库中。以下是我的代码:

数据库(用户方法)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 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();
}
}

注册活动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<?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>

我对此进行了大量研究并尝试了一些不同的方法,但我需要在注册活动中运行注册方法,如果一切正常,那么我需要检查电子邮件和密码然后将它们都存储起来。任何和所有的帮助将不胜感激。


首先,您可以将以下方法添加到您的数据库(用户方法)类中:-

1
2
3
4
5
6
7
8
9
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;
}

然后你可以在 register 方法的适当位置包含一个检查,沿着

的行

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

或者你可以改变:-

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

成为:-

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

额外的

您似乎也没有调用 insertUser 方法来实际添加用户。

我建议对寄存器 mnethod 进行以下更改:-

1
2
3
4
5
6
7
8
9
10
11
12
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();
        }
    }
}