社内se × プログラマ × ビッグデータ

プログラミングなどITに興味があります。

Android(kotlin) SQLite データの挿入

編集するファイル

以下の記事で作成したプロジェクトを引き続き編集していきます。
blueskyarea.hatenablog.com

  • MainActivity.kt
データ保存処理(MainActivity.kt)

データの保存処理と言いながら、更新処理を書いています。
update を使用する方法もありますが、ここでは、delete -> insert という流れで更新処理を実現しようとしています。

    fun onSaveButtonClick(view: View) {
        Log.d("MainActivity", "Called onSaveButtonClick()")
        // Find EditText for description
        val etNote = findViewById<EditText>(R.id.etNote)

        // Get input description
        val note = etNote.text.toString()

        // Get database connection object
        val db = dbHelper.writableDatabase

        // Statement for Delete
        val sqlDelete = "DELETE from levels WHERE _id = ?"
        var stmt = db.compileStatement(sqlDelete)
        stmt.bindLong(1, levelId.toLong())
        stmt.executeUpdateDelete()

        // Statement for Insert
        val sqlInsert = "INSERT into levels (_id, name, description) values (?, ?, ?)"
        stmt = db.compileStatement(sqlInsert)
        stmt.bindLong(1, levelId.toLong())
        stmt.bindString(2, levelName)
        stmt.bindString(3, note)
        stmt.executeInsert()

        // Clear the description
        etNote.setText("")
        // Find TextView for Level name
        val tvLevelName = findViewById<TextView>(R.id.tvSelectedLevel)
        // Set the Level name as None
        tvLevelName.text = getString(R.string.tv_name)
        // Find Button for save
        val btnSave = findViewById<Button>(R.id.btnSave)
        // Disable the button
        btnSave.isEnabled = false
    }

メモ
データベース処理に関しての基本的な流れ
1. データベース接続オブジェクトを取得
2. SQL文字列を作成
3. SQL文字列を元にステートメントオブジェクトを取得
4. 変数をバインド
5. SQLを実行

ビルド・実行

Run ボタンをクリックし、エミュレータを起動します。
レベルを選択し、何らかの文字列を入力して、保存ボタンをタッチすると、データの挿入処理が実行されます。
f:id:blueskyarea:20200504183327p:plain
また、前回の記事では呼び出されなかった"テーブルの生成処理"が動作していることが確認できました。
f:id:blueskyarea:20200504183425p:plain
device file explorer 上で同期ボタンをクリックしてみると
f:id:blueskyarea:20200504183509p:plain
databases ディレクトリが生成され、中にデータベースファイル(level.db)が生成されていることも確認できました。
f:id:blueskyarea:20200504183601p:plain

やはりデータベースヘルパークラスをクラス変数として定義するだけでは、onCreate() は実行されないようです。
きちんと確認はしていませんが、データベースコネクション用のオブジェクトを生成されたタイミングで初めて呼び出されるのではないかと思われます。

val db = dbHelper.writableDatabase

また、データベースヘルパークラスの onCreate() はデータベースが存在しないときに1回だけ実行される仕様のため、もし onCreate() を修正した場合、データベースを削除しないと動作確認が出来ないことに注意する必要があります。