Search code examples
androidkotlinandroid-sqliteanko

How to define a not null field for a table of SQLite when I use Anko in Kotlin?


I hope to define a not null field for a table of SQLite when I use Anko in Kotlin.

But DBRecordTable.Category to TEXT NOT NULL is wrong ,how can I fix it?

Code

  implementation "org.jetbrains.anko:anko-sqlite:$anko_version"

  override fun onCreate(db: SQLiteDatabase) {
        db.createTable( DBRecordTable.TableNAME , true,
            DBRecordTable._ID to INTEGER + PRIMARY_KEY+ AUTOINCREMENT,
            DBRecordTable.Category to TEXT NOT NULL,    //It's wrong
            DBRecordTable.Content to TEXT,
            DBRecordTable.IsFavorite to INTEGER  +DEFAULT("0"),
            DBRecordTable.IsProtected to INTEGER  +DEFAULT("0"),
            DBRecordTable.CreatedDate to INTEGER
        )
    }

Solution

  • By taking a look at sqlTypes.kt we can find that the not null constraint is defined as following:

    val NOT_NULL: SqlTypeModifier = SqlTypeModifierImpl("NOT NULL")

    So your code should be:

    override fun onCreate(db: SQLiteDatabase) {
        db.createTable( DBRecordTable.TableNAME , true,
            DBRecordTable._ID to INTEGER + PRIMARY_KEY + AUTOINCREMENT,
            DBRecordTable.Category to TEXT + NOT_NULL,
            DBRecordTable.Content to TEXT,
            DBRecordTable.IsFavorite to INTEGER + DEFAULT("0"),
            DBRecordTable.IsProtected to INTEGER + DEFAULT("0"),
            DBRecordTable.CreatedDate to INTEGER
        )
    }