Hussein Yassine
Hussein Yassine

Reputation: 63

SQLiteConstraintException constraint failed

I'm getting an exception whenever I try to insert to my clients table. This is the client table:

db.execSQL("CREATE TABLE " + TABLE_CLIENTS + " (" +
                COLUMN_CID + " INTEGER PRIMARY KEY, " +
                COLUMN_CLIENTNAME + " TEXT, " + COLUMN_ADDRESS + " TEXT, " + COLUMN_LOANAMOUNT + " DECIMAL)");

This is the insertion method:

public long addClients(Client c) {
    ContentValues cv = new ContentValues();
    cv.put(COLUMN_CID, c.getCId());
    cv.put(COLUMN_CLIENTNAME, c.getCName());
    cv.put(COLUMN_ADDRESS, c.getAddress());
    cv.put(COLUMN_LOANAMOUNT, c.getLoanamount());

    return ourDatabase.insert(TABLE_CLIENTS, null, cv);
}

The object is being read in the LogCat just fine, all the attributes are correct.

Logcat: Logcat:

 2.017 25026-25026/com.example.androidserversocket 
    D/sa:﹕ 0 Hussein Nabatieh 32 08-06 15:12:12.017 25026-25026/com.example.androidserversocket 
    D/type:﹕ C 08-06 15:12:12.017 25026-25026/com.example.androidserversocket 
    D/Client:﹕ in c 08-06 15:12:12.027 25026-25026/com.example.androidserversocket 
    E/SQLiteDatabase﹕ Error inserting loanamount=32.0 address=Nabatieh cid=0 cname=Hussein android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed

Upvotes: 0

Views: 86

Answers (2)

CL.
CL.

Reputation: 180270

Your problem is that a row with the same cid value already exists.

An INTEGER PRIMARY KEY column can automatically get an unused value, but this is done only when you don't explicit put a value for this column into the ContentValues object.

Upvotes: 0

LaurentY
LaurentY

Reputation: 7653

It seems ID of c.getCId() already exists in table.

Try a SELECT on this ID before, if exist maybe you have to do an UPDATE.

Upvotes: 1

Related Questions