如何使插入的数据持久保存在 Room 数据库中?

问题描述 投票:0回答:0

我正在努力将永久数据插入到我预先填充的数据库中。

Screenshot of data being added into database

这是将数据添加到数据库中的代码

dialogBinding.btnYes.setOnClickListener {
    val cantoneseWord = dialogBinding.etAddCantoneseWord.text.toString()
    val englishWord = dialogBinding.etAddEnglishWord.text.toString()
    when {
        dialogBinding.etAddCantoneseWord.text.isNullOrEmpty() -> {
            Toast.makeText(this, "Please enter a Cantonese word/phrase", Toast.LENGTH_SHORT).show()
        }
        dialogBinding.etAddEnglishWord.text.isNullOrEmpty() -> {
            Toast.makeText(this, "Please enter a English word/phrase", Toast.LENGTH_SHORT).show()
        } else -> {
        val newWord = WordEntity(0, cantoneseWord, englishWord, true)
        lifecycleScope.launch {
            // withContext(Dispatchers.IO) suspends the coroutine and switches the execution to a background thread pool provided by the 'Dispatchesr.IO' dispatcher.
            // This avoids blocking the main thread which could cause the UI to freeze or become unresponsive.
            withContext(Dispatchers.IO) {
                wordDao.addWord(newWord)
                setupWordRecyclerView(wordDao)
            }
        }
        Toast.makeText(this@SearchActivity, "Successfully added", Toast.LENGTH_SHORT).show()
        wordDialog.dismiss()
    }
    }
}

这是创建数据库的代码

fun getInstance(context: Context): WordDatabase {
    synchronized(this) {
        var instance = INSTANCE

        if (instance == null) {
            instance = Room.databaseBuilder(
                context.applicationContext,
                WordDatabase::class.java,
                "CantoWords"
            ).fallbackToDestructiveMigration()
                .createFromAsset("database/CantoWords_shortened.db").build()
            INSTANCE = instance
        }
        return instance
    }
}

我能够成功地将数据插入数据库(如第一个屏幕截图 ID 7 - 测试所示),但是如果我重新启动应用程序,重新安装它或提取数据库并在 DB Browser for SQLite 上查看它,ID 7 会消失。

android kotlin insert android-room persistence
© www.soinside.com 2019 - 2024. All rights reserved.