ISO
ISO

Reputation: 11

Kotlin SQLiteOpenHelper failing to insert data into table

class SQLiteHelper(context: Context?) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION){

companion object{
    private const val DATABASE_VERSION = 1
    private const val DATABASE_NAME = "notes.db"
    private const val TBL_NOTES = "tbl_notes"
    private const val ID = "id"
    private const val TITLE = "title"
    private const val TEXT = "text"
    private const val FAVOURITE = "favourite"
}


override fun onCreate(db: SQLiteDatabase?) {
    val createTblNotes = ("CREATE TABLE " + TBL_NOTES + "("
            + ID + "INTEGER PRIMARY KEY,"
            + TITLE + "TEXT,"
            + TEXT + "TEXT,"
            + FAVOURITE + "INTEGER" + ")")

    db?.execSQL(createTblNotes)
}

override fun onUpgrade(db:SQLiteDatabase?, oldVersion:Int, newVersion:Int) {
    db!!.execSQL("DROP TABLE IF EXISTS $TBL_NOTES")
    onCreate(db)
}

fun insertNote(note:Note) : Long{
    val db : SQLiteDatabase = this.writableDatabase

    val contentValues = ContentValues()
    contentValues.put(ID, note.id)
    contentValues.put(TITLE, note.title)
    contentValues.put(TEXT, note.text)
    contentValues.put(FAVOURITE, note.favourite)

    val success = db.insert(TBL_NOTES, null, contentValues)
    db.close()

    return success
}

}

class AddNoteFragment : Fragment() {

private lateinit var sqLiteHelper: SQLiteHelper

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val view = inflater.inflate(R.layout.fragment_add_note, container, false)

    val etTitle = view.findViewById<EditText>(R.id.editTextTitle)
    val etText = view.findViewById<EditText>(R.id.editTextText)

    val btnSave = view.findViewById<Button>(R.id.buttonSave)

    sqLiteHelper = SQLiteHelper(context)

    btnSave.setOnClickListener{
        val title = etTitle.text.toString()
        val text = etText.text.toString()

        val note = Note(title = title, text = text, favourite = 0)
        val status = sqLiteHelper.insertNote(note)

        if(status > -1){
            Toast.makeText(this.context, "Note added", Toast.LENGTH_LONG).show()
        }else{
            Toast.makeText(this.context, "Note not added", Toast.LENGTH_LONG).show()
        }
    }

    return view
}

}

It keeps showing message "Data not added" despite not showing any errors or warinings, above is SQLiteHelper class and fragment where it is being used

Upvotes: -1

Views: 27

Answers (1)

ISO
ISO

Reputation: 11

Issue was that there was already a table without that column

Upvotes: 0

Related Questions