Brandon
Brandon

Reputation: 103

Android SQLite not autoincrementing

I have been trying to figure out why my autoincrement id column isn't working. The table inserts fine, however, as soon as I try and insert another row, the id column isn't incrementing. It just tries to insert the next row with id of 0. Any help would be greatly appreciated!

Below is the column metadata (name and type) and my create table sql within the db.execSQL() method:

ID(BaseColumns._ID, "INTEGER"),
YEAR("year", "real"),
MAKE("make", "text"),
MODEL("model", "text"),
STYLE("style", "text"),
COLOR("color", "text"),
ALT_COLOR("altColor", "text"),
CLASS("class", "text"),
CLASS_CODE("classCode", "text");

db.execSQL("CREATE TABLE " + TABLE_NAME + " (" 
+ Columns.ID.getName() + " " + Columns.ID.getType()+ " PRIMARY KEY AUTOINCREMENT" + ", "   + Columns.YEAR.getName() + " " + Columns.YEAR.getType() + ", " 
+ Columns.MAKE.getName() + " " + Columns.MAKE.getType() + ", " 
+ Columns.MODEL.getName() + " " + Columns.MODEL.getType() + ", " 
+ Columns.STYLE.getName() + " " + Columns.STYLE.getType() + ", " 
+ Columns.COLOR.getName() + " " + Columns.COLOR.getType() + ", " 
+ Columns.ALT_COLOR.getName() + " " + Columns.ALT_COLOR.getType() + ", " 
+ Columns.CLASS.getName() + " " + Columns.CLASS.getType() + ", " 
+ Columns.CLASS_CODE.getName() + " " + Columns.CLASS_CODE.getType() + ");");

Upvotes: 1

Views: 610

Answers (2)

Brandon
Brandon

Reputation: 103

I found out that when sending in ContentValues to the context.getContentResolver().insert(uri, values) method, your ContentValues should not include a key/value pair containing an id. This is what was causing my _id column not to auto-increment.

Upvotes: 0

laalto
laalto

Reputation: 152827

01-16 05:51:09.882: E/Database(1177): Error inserting model=SHELBY CONV. style= _id=0 color=KONA BLUE classCode=JCA class=JCA - 2012-15 - ALL year=2012 altColor= make=FORD
01-16 05:51:09.882: E/Database(1177): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed 

You should not define the ID column value in the insert, as evidenced by _id=0 in the exception. Autoincrement only works if the column value is not specified:

If no ROWID is specified on the insert, or if the specified ROWID has a value of NULL, then an appropriate ROWID is created automatically.

Upvotes: 2

Related Questions