Do not add to database when some value is null

Asked

Viewed 27 times

0

How do I not add to the database when the String dia is null ?

Code :

      public boolean insertData(String disciplina,String sala,String dia,String hora){
    ContentValues values = new ContentValues();
    values.put(COL_2,disciplina);
    values.put(COL_3,sala);
    values.put(COL_4,dia);
    values.put(COL_5,hora);
    long result = database.insert(TABLE_NAME,null,values);
        if(result==-1){
            return false;
        }else
            return true;


}
  • NOT NULL in the database column

  • What do you mean ? You can elaborate on a response ?

  • when creating the database table, have column Name Datatype NOT Nulll Flags Default Value Comment, just tick NOT NULL

1 answer

2


You have 2 options:

1) Define in the table creation that the column cannot receive nulls and, if you try to insert null, the bank puts a default value. Ex:

CREATE TABLE tabela (coluna TEXT NOT NULL DEFAULT 'texto qualquer');

2) Define in the table creation that the column cannot receive nulls and the method you insert has to check before and abort if the value is null. Ex:

CREATE TABLE tabela (coluna TEXT NOT NULL);

In the method:

public boolean insertData(String valor_coluna){
    if(valor_coluna == null || TextUtils.isEmpty(valor_coluna)) return false;

    ContentValues values = new ContentValues();
    values.put(coluna, valor_coluna);

    return database.insert(TABLE_NAME,null,values) != -1;
}
  • Exactly as I had thought. Even so it is more indicated to change the database and the method that makes the insertion.

  • It’s two different strategies. There are cases where you want to set a default value and do not need to care about the insertion (type data you would probably fill most with the same default value, so it is easier to insert a null and the database fixes) or there are cases that cannot be null and you don’t even want a default value.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.