首页 > 解决方案 > 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;
    }
}

标签: javaandroidsqlite

解决方案


您的代码似乎很好,但您不应该这样做,因为在您遍历所有email列表时可能会发生另一个插入。最好创建启用约束的email字段,UNIQUE然后直接插入数据库以创建电子邮件。如果已经存在,这将导致异常email,您可以适当地捕获和处理。


推荐阅读