【问题标题】:I have a problem about using sqlite in Android Studio Kotlin我在 Android Studio Kotlin 中使用 sqlite 时遇到问题
【发布时间】:2022-01-24 00:40:42
【问题描述】:
【问题讨论】:
标签:
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()
}
}
}