我希望在Kotlin中使用Anko时为SQLite表定义一个非null字段。

但是DBRecordTable.Category to TEXT NOT NULL是错误的,我该如何解决?

代码

  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
        )
    }

最佳答案

通过查看 sqlTypes.kt ,我们可以发现not null约束的定义如下:



因此,您的代码应为:

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
    )
}

10-08 03:24