James Dickens James Dickens - 1 year ago 97
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) {
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");

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
statement. Any insights as to why this is happening much appreciated.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download