13

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)";
2
  • eek you should really consider using the SQLiteDatabase insert method rather than creating these raw string statements
    – james
    Nov 9, 2011 at 19:20
  • Agreed. It's unwieldy code however the circumstances didn't allow for an alternative method. Also, anyone following this thread should be forewarned that unsanitized/unescaped user input in an SQL insert statement, as shown above, is cause for egregious 'eek'.
    – wufoo
    Sep 19, 2013 at 19:50

1 Answer 1

31

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.

1
  • Thanks a lot, I've run into a similar issue and your solution helped me to move on. However, I must admit that removing NOT NULL is surprisingly unobvious in such a case.
    – nbulba
    Jun 12, 2012 at 10:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.