关于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>

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

  • java文件中的注册方法只是检查所有字段是否不为空……我应该将它扩展到db吗?
  • 如果电子邮件不存在,我想运行该方法来验证字段,然后存储电子邮件和密码


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

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();
        }
    }
}
  • 这看起来很棒,而且非常详细。谢谢!
  • 对我来说很短:)
  • 如果它有效并回答了您的问题,请勾选此作为答案。
  • 我已经准备好一切,我正在测试应用程序,但每次我尝试访问该页面时,我的应用程序仍然崩溃,有什么想法可以调查这个问题吗?
  • 它失败了什么? (编辑问题以包括堆栈跟踪)。在进行我建议的更改之前它是否有效?
  • 这是我添加到数据库但无关紧要的东西,我为panic道歉。然而。当我现在运行代码时,所有字段都被检查,它让我知道该帐户已创建,但如果我返回并添加相同的电子邮件,该应用程序允许我使用相同的电子邮件……
  • 好的,从我可以看到您在验证后没有调用 insertUser 方法。因此,在 onSignupSuccess() 中,您需要调用 insertUser 方法检查结果并发出相应的 toast,即 <1 没有插入,>0 然后它确实插入了。
  • 您不应该检查电子邮件计数是否小于或等于 1 以使其唯一吗?
  • @cricket_007 我已经这样做了,因为我在写评论时,沿着结果变量的行,即从插入方法返回的 long。
  • 我只是说。现在,检查 WHERE 子句在逻辑上返回的计数小于 1 表示电子邮件根本不存在
  • 哦,这就是它检查电子邮件是否唯一的目的。所以 1 表示它不是唯一的。即如果 count < 1 则 true 电子邮件是唯一的电子邮件,否则它存在所以 false(1 或更多),因为它不是唯一的。即,这是作为插入之前的检查完成的(尝试按照 OP 的逻辑进行)。
  • 所以它不允许我将两个字符串放入 insertUser,但它允许我使用 insertUserData 方法。这似乎解决了这个问题……我会尽快更新。我应该如何选择您的回答作为答案?
  • Ooops 没有检查签名(实际上首先查看了 insertUserData,所以假设相同)。勾选勾号以将问题标记为已回答。
  • 来了,老大。


来源:https://www.codenong.com/49833221/

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?