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

  public void onCreate(SQLiteDatabase db) {

        String query= "CREATE TABLE " + ChallengesEntry.DB_TABLE  + " ("
                +ChallengesEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                +ChallengesEntry.DB_COLUMN + " TEXT , "
                +ChallengesEntry.DB_COLUMN_DAYS + " TEXT);";

        db.execSQL(query);
    }

THIS IS MY EDITOR ACTIVITY CLASS

  @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_save:
                insertTask();
                // Exit activity
                finish();
                return true;

            case android.R.id.home:
                // Navigate back to parent activity (CatalogActivity)
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }

        return super.onOptionsItemSelected(item);

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button1:

                final EditText editText =  new EditText(this);
                AlertDialog dialog = new AlertDialog.Builder(this)
                        .setTitle("Add new Challenge")
                        .setMessage("Whats your Challenge")
                        .setView(editText)
                        .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String task = String.valueOf(editText.getText());
                                insertDay(task);
                            }
                        })
                        .setNegativeButton("CANCEL", null)
                        .create();
                dialog.getWindow().getAttributes().windowAnimations=R.style.DialogAnimation;
                dialog.show();


        }

    }
    //TEMPORARY SOLUTION
    public void insertDay(String task) {

        DbHelper mDbHelper = new DbHelper(this);
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(ChallengesEntry.DB_COLUMN_DAYS,task );
        db.insertWithOnConflict(ChallengesEntry.DB_TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
        db.close();

    }

    public void insertTask(){

        String name=editChallengeName.getText().toString().trim();
        DbHelper mDbHelper = new DbHelper(this);
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(ChallengesEntry.DB_COLUMN,name);
        db.insertWithOnConflict(ChallengesEntry.DB_TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
        db.close();

    }

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:

+ChallengesEntry.DB_COLUMN + " TEXT , "

to

+ChallengesEntry.DB_COLUMN + " TEXT NOT NULL, "

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:

public boolean insertData(String taskName, String days){
    DbHelper mDbHelper = new DbHelper(this);
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(ChallengesEntry.DB_COLUMN,taskName);
    values.put(ChallengesEntry.DB_COLUMN_DAYS,days);
    boolean result = db.insert(ChallengesEntry.DB_TABLE, null, values) >= 0;
    db.close();
    return result;
}

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

boolean successful = insertData(taskName, days);

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

long taskId = 0; 

This method will insert the taskname:

private long insertTask(){
    String name = editChallengeName.getText().toString().trim();
    if (name.isEmpty())
        return -1;
    DbHelper mDbHelper = new DbHelper(this);
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(ChallengesEntry.DB_COLUMN, name);
    long id = db.insert(ChallengesEntry.DB_TABLE, null, values);
    db.close();
    return id;
}

you call it where you had insertTask();:

taskid = insertTask();

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

private void insertDay(String task) {
    DbHelper mDbHelper = new DbHelper(this);
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(ChallengesEntry.DB_COLUMN_DAYS, task );
    db.update(ChallengesEntry.DB_TABLE, values, ChallengesEntry.DB_COLUMN + "=" + taskid, null);
    db.close();
}

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