Skip to content
Advertisement

SQLiteConstraintException:NOT NULL constraints android

I have a an Editor Activity where i insert my data in the database.

I’ve created 3 columns as :-

  • ID INTEGER,
  • Task TEXT NOT NULL and
  • Days TEXT.

I insert data into the Task column with data from an edit text and insert other data into the Days column by creating an alert dialog containing an edit text.

I’m successfully able to insert data into the Task column but when i insert data from the alert dialog into the Days column, I get this error :-

“android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: Task.TaskName (code 1299)”.

Please help me with this.I know there are same question available but android studio doesn’t help much in debugging the sq lite database and also the error are different for all,keeping in mind that please,please don’t mark this question as duplicate.

THIS IS MY SQLITE CREATION SYNTAX

JavaScript

THIS IS MY EDITOR ACTIVITY CLASS

JavaScript

Advertisement

Answer

Your CREATE TABLE statement does not include NOT NULL for the column TaskName, although you say that it is defined as NOT NULL.
So this is the 1st inconsistency.
You must change this line:

JavaScript

to

JavaScript

then uninstall the app from the emulator/device so the db is deleted
and then rerun the app so the db and the table is recreated as it is supposed to be.
But there is a case that the table is already created with NOT NULL for the column TaskName and maybe you made changes to your code that don’t reflect the real state of the table.
If this is the case then there is a reason for the error you get:
You have 2 different methods:
insertTask() and insertDay() to insert data to your table! Why?
This means that every row of your table will have an ID and only 1 column with data,
the other will be empty (null).
Is this what you want? I don’t think so.
So if the column TaskName is defined NOT NULL and you execute insertDay(),
then you get the error because TaskName in that row has no value (it is null)
and this is not allowed.
So get the data from the EditText and the AlertDialog
and save it to the table with 1 insert statement, like this:

JavaScript

This method returns true or false if the insertion is successful. You can call it like this:

JavaScript

where taskname and days are the values you collected from the EditText and the AlertDialog.
Edit
Declare this variable in your activity class:

JavaScript

This method will insert the taskname:

JavaScript

you call it where you had insertTask();:

JavaScript

then this method will update the row with id = taskid:

JavaScript

and you call it just like you called the previous insertDay()

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement