James Dickens James Dickens - 17 days ago 9
Java Question

Unique Login and SQLiteConstraintException

I have the following code for inserting login information into an SQLite database.

public boolean addLogin(Login login) {
SQLiteDatabase Db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TABLE1_COL1, login.getUser_Name());
values.put(TABLE1_COL2, login.getPassword());
try {
Db.insert(TABLE1_NAME, null, values);
} catch (SQLiteConstraintException ex) {
System.out.println("here");
return false;
}

return true;
}


When I try to test my code with this method executed in my main activity:

//Testing Adding Logins
Login login1 = new Login("having1", "fun1");
Login login2 = new Login("having1", "fun1");
db.addLogin(login1);
db.addLogin(login2);


I get the error:

E/SQLiteDatabase: Error inserting User_Names=having1 Password=fun1
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: Login_Table.User_Names (code 1555)


But isn't this what the try and catch statement is supposed to prevent? I also do not see the
System.out.println("here")
statement. Any insights as to why this is happening much appreciated.

Answer

Then you should use insertOrThrow() method. insert() just returns -1 if failed.