【问题标题】:I have a problem about using sqlite in Android Studio Kotlin我在 Android Studio Kotlin 中使用 sqlite 时遇到问题
【发布时间】:2022-01-24 00:40:42
【问题描述】:

当我单击按钮时,我将随机数据发送到文本视图,但它只能工作一次,那么当我多次单击时如何获取更改的数据? 谢谢你的帮助 You can see the code

【问题讨论】:

  • 您可能会通过发布代码图像来拒绝投票和/或关闭问题。我建议在阅读 stackoverflow.com/help/how-to-ask 后编辑您的问题,尤其是用代码替换链接的图像。

标签: android-studio kotlin android-sqlite


【解决方案1】:

问题

您的问题是您使用的是相同的光标,因此整个值都是因为 val cursor=db.rawquery .... 行不在侦听器的正文中。

修复

您需要在侦听器主体内刷新光标。您可以通过将该行复制到侦听器中来完成此操作。

建议

我建议将侦听器的主体设为一个函数,然后您只需从侦听器中调用该函数即可。然后,您可以调用该函数来初始显示单词。

工作示例

这是一个使用此类功能的示例(而不是选项卡使用 TextViews):-

class MainActivity : AppCompatActivity() {
    lateinit var db: databasehelper
    lateinit var arabicword: TextView
    lateinit var englishword: TextView
    lateinit var frenchword: TextView
    lateinit var russianword: TextView
    lateinit var turkishword: TextView
    lateinit var ukranianword: TextView
    lateinit var changeword: Button
    lateinit var binding: MainActivity


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        arabicword = this.findViewById(R.id.arabic)
        englishword = this.findViewById(R.id.english)
        frenchword = this.findViewById(R.id.french)
        russianword = this.findViewById(R.id.russian)
        turkishword = this.findViewById(R.id.turkish)
        ukranianword = this.findViewById(R.id.ukranian)
        changeword = this.findViewById(R.id.changeword)
        binding = this

        db = databasehelper(applicationContext)
        setWords() // INITIAL DISPLAY
        /* Simplifeied Listener */
        changeword.setOnClickListener(View.OnClickListener {
            setWords()
        })
    }

    @SuppressLint("Range")
    fun setWords() {
        var cursor = db.writableDatabase.rawQuery("SELECT * FROM words ORDER BY random() LIMIT 1",null)
        /* only need to move to the first as only 1 rows returned */
        /* also directly sets the Texts without intermediate ArrayList */
        if (cursor.moveToFirst()) {
            binding.arabicword.setText(cursor.getString(cursor.getColumnIndex("arabicword")))
            binding.englishword.setText(cursor.getString(cursor.getColumnIndex("englishword")))
            binding.frenchword.setText(cursor.getString(cursor.getColumnIndex("frenchword")))
            binding.russianword.setText(cursor.getString(cursor.getColumnIndex("russianword")))
            binding.turkishword.setText(cursor.getString(cursor.getColumnIndex("turkishword")))
            binding.ukranianword.setText(cursor.getString(cursor.getColumnIndex("ukranianword")))
        } else {
            Toast.makeText(this,"Ooops not changed",Toast.LENGTH_SHORT).show()
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多