java - Problem to insert new user to DB after checking if email exist sqlite
问题描述
I'm trying to prevent double insertion of users to DB and when i check email every time I get the message:
my email already exists
Thanks for answering.
Check if userEmail
already exists: DataBaseHelper
class:
public boolean checkIfExists(String userEmail){
db = this.getReadableDatabase();
String query = "select "+ COL_EMAIL + " from " +TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String existEmail;
if (cursor.moveToFirst()) {
do {
existEmail = cursor.getString(0);
if (existEmail.equals(userEmail)) {
return true;
}
} while (cursor.moveToNext());
}
return false;
}
Validate Email, check if email already exists: Registration
class:
private boolean validateEmail() {
String emailInput = textInputEmail.getEditText().getText().toString().trim();
if (myDb.checkIfExists(emailInput)) {
textInputEmail.setError("Email already exist");
return false;
} else if (emailInput.isEmpty()) {
textInputEmail.setError("Field can't be empty");
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) {
textInputEmail.setError("Please enter a valid email address");
return false;
} else {
textInputEmail.setError(null);
return true;
}
}
解决方案
您的代码似乎很好,但您不应该这样做,因为在您遍历所有email
列表时可能会发生另一个插入。最好创建启用约束的email
字段,UNIQUE
然后直接插入数据库以创建电子邮件。如果已经存在,这将导致异常email
,您可以适当地捕获和处理。
推荐阅读
- c - C中递归函数中的内存泄漏
- docker - CSRF 与 AWS Fargate 上的 dockerized Flask 应用程序
- mongodb - $group 和 $slice 每个组的更快 mongodb 聚合以进行大量收集
- java - Spring Boot“无法执行 CommandLineRunner 错误”
- c++ - Makefile 的未定义符号问题
- navigator - navigator.connection 下行显示最大10Mbps
- javascript - 如何在javascript中的json响应上使用map函数?
- javascript - 带有字符串插值的 React.js 类名值
- android - 找到所需的转换:MaterialContainerTransform?
- odata - 循环通过 createEntry() 创建的对象列表并在执行 submitChange() 之前编辑它们的属性