wufoo
wufoo

Reputation: 14571

Android: inserting sqlite record with AUTOINCREMENT column

I have an sqlite database on android created like this:

sqlite> .schema
CREATE TABLE criterion ('_id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, active text, important text, sort int, summary text, user text, category_id int, entrytype int);

The only way I can insert a record into this table is by specifying a value for _id which I want to auto-increment. This is the only way I can get the insert working:

recid = totalrecs + 1;
String q = "insert into criterion (_id, active, important, sort, summary, user, category_id, entrytype) values (" + recid + ", \"1\", \"0\", 99, \"foobar\", \"1\", 99, 0)";
Log.d (TAG, "query:" + q);
mDb.execSQL (q);

If I leave the _id column out and don't specify a value for _id, I get an error:

android.database.sqlite.SQLiteConstraintException: criterion._id may not be NULL: insert into criterion(active, important, sort, summary, user, category_id, entrytype) values ("1", "0", 99, "foobar", "1", 99, 0)

How do I arrange the query (or schema) so Android will take care of incrementing the _id column?

Update/fixed 2 lines above (removed NOT NULL, removed _id from query):

CREATE TABLE criterion ('_id' INTEGER PRIMARY KEY AUTOINCREMENT, active text, important text, sort int, summary text, user text, category_id int, entrytype int);

String q = "insert into criterion (active, important, sort, summary, user, category_id, entrytype) values (\"1\", \"0\", 99, \"foobar\", \"1\", 99, 0)";

Upvotes: 13

Views: 26320

Answers (1)

Geekswordsman
Geekswordsman

Reputation: 1307

Remove the NOT NULL from the schema and you're golden.

Clarifying: Specifying NOT NULL on an auto-increment column makes it so the auto-increment doesn't function. The NOT NULL is what is making it so you have to specify the _id.

Once you remove it, and don't include the _id in the insert statement, SQL will receive the _id as NULL and automatically handle setting the _id for you.

Upvotes: 31

Related Questions