当我在Kotlin中使用Anko时,如何为SQLite表定义一个非空字段?

时间:2018-11-15 07:58:48

标签: android kotlin android-sqlite anko

当我在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
        )
    }

2 个答案:

答案 0 :(得分:2)

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

  

val NOT_NULL: SqlTypeModifier = SqlTypeModifierImpl("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
    )
}

答案 1 :(得分:1)

我们使用了这些代码行,并且可以很好地创建表格

private val dbName = THE_PATH +"JSANotes.db"
private val dbTable = "Notes"
private val colId = "Id"
private val colTitle = "Title"
private val colContent = "Content"
private val dbVersion = 1

private val CREATE_TABLE_SQL = "CREATE TABLE IF NOT EXISTS " + dbTable + " (" + colId + " INTEGER PRIMARY KEY," + colTitle + " TEXT, " + colContent + " TEXT NOT NULL);"
private var db: SQLiteDatabase? = null

init {
    val dbHelper = DatabaseHelper(context)
    db = dbHelper.writableDatabase
}

此站点将帮助解决许多SQLite问题LINK

我们不使用NOT NULL代替NOT NULL

            if(edtContent.text.toString().equals("")){
            error("ENTER Content")
            edtContent.requestFocus()
            return@setOnClickListener
        }

您还可以使用此代码测试在活动底部的文本视图中显示的错误消息的长度

        fun error(msg:String){
        object : CountDownTimer(4000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                tvError.visibility = View.VISIBLE
                tvError.setText(msg)
            }
            override fun onFinish() {
                tvError.visibility = View.INVISIBLE
                tvError.setText("")
            }
        }.start()
    }